1 """Miscellaneous functions for the mudpy engine."""
3 # Copyright (c) 2004-2016 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, filename=None, old_style=False):
27 """Set up a new element."""
29 # TODO(fungi): This can be removed after the transition is complete
30 self.old_style = old_style
32 # keep track of our key name
35 # keep track of what universe it's loading into
36 self.universe = universe
38 # clone attributes if this is replacing another element
39 if self.old_style and self.key in self.universe.contents:
40 old_element = self.universe.contents[self.key]
41 for attribute in vars(old_element).keys():
42 exec("self." + attribute + " = old_element." + attribute)
44 self.owner.avatar = self
46 # i guess this is a new element then
49 # set of facet keys from the universe
50 self.facethash = dict()
52 # not owned by a user by default (used for avatars)
55 # no contents in here by default
58 # parse out appropriate category and subkey names, add to list
59 if self.key.find(":") > 0:
60 self.category, self.subkey = self.key.split(":", 1)
62 self.category = "other"
63 self.subkey = self.key
64 if self.category not in self.universe.categories:
65 self.category = "other"
66 self.subkey = self.key
68 # get an appropriate filename for the origin
70 filename = self.universe.default_origins[self.category]
71 if not os.path.isabs(filename):
72 filename = os.path.abspath(filename)
74 # add the file if it doesn't exist yet
75 if filename not in self.universe.files:
76 mudpy.data.DataFile(filename, self.universe)
78 # record or reset a pointer to the origin file
79 self.origin = self.universe.files[filename]
81 # add a data section to the origin if necessary
82 if self.key not in self.origin.data:
83 self.origin.data[self.key] = {}
85 # add or replace this element in the universe
86 self.universe.contents[self.key] = self
87 self.universe.categories[self.category][self.subkey] = self
90 """Create a new element and replace this one."""
91 Element(self.key, self.universe, self.origin.filename,
92 old_style=self.old_style)
96 """Remove an element from the universe and destroy it."""
97 del(self.origin.data[self.key])
98 del self.universe.categories[self.category][self.subkey]
99 del self.universe.contents[self.key]
103 """Return a list of non-inherited facets for this element."""
106 return self.origin.data[self.key].keys()
107 except (AttributeError, KeyError):
110 return self.facethash
112 def has_facet(self, facet):
113 """Return whether the non-inherited facet exists."""
114 return facet in self.facets()
116 def remove_facet(self, facet):
117 """Remove a facet from the element."""
118 if self.has_facet(facet):
119 del(self.origin.data[self.key][facet])
120 self.origin.modified = True
123 """Return a list of the element's inheritance lineage."""
124 if self.has_facet("inherit"):
125 ancestry = self.get("inherit")
128 for parent in ancestry[:]:
129 ancestors = self.universe.contents[parent].ancestry()
130 for ancestor in ancestors:
131 if ancestor not in ancestry:
132 ancestry.append(ancestor)
137 def get(self, facet, default=None):
138 """Retrieve values."""
143 return self.origin.data[self.key][facet]
145 return self.origin.data[".".join((self.key, facet))]
146 except (KeyError, TypeError):
148 if self.has_facet("inherit"):
149 for ancestor in self.ancestry():
150 if self.universe.contents[ancestor].has_facet(facet):
151 return self.universe.contents[ancestor].get(facet)
155 def set(self, facet, value):
157 if not self.has_facet(facet) or not self.get(facet) == value:
159 if self.key not in self.origin.data:
160 self.origin.data[self.key] = {}
161 self.origin.data[self.key][facet] = value
163 node = ".".join((self.key, facet))
164 self.origin.data[node] = value
165 self.facethash[node] = self.origin.data[node]
166 self.origin.modified = True
168 def append(self, facet, value):
169 """Append value to a list."""
170 newlist = self.get(facet)
173 if type(newlist) is not list:
174 newlist = list(newlist)
175 newlist.append(value)
176 self.set(facet, newlist)
186 add_terminator=False,
189 """Convenience method to pass messages to an owner."""
202 def can_run(self, command):
203 """Check if the user can run this command object."""
205 # has to be in the commands category
206 if command not in self.universe.categories["command"].values():
209 # avatars of administrators can run any command
210 elif self.owner and self.owner.account.get("administrator"):
213 # everyone can run non-administrative commands
214 elif not command.get("administrative"):
217 # otherwise the command cannot be run by this actor
221 # pass back the result
224 def update_location(self):
225 """Make sure the location's contents contain this element."""
226 area = self.get("location")
227 if area in self.universe.contents:
228 self.universe.contents[area].contents[self.key] = self
230 def clean_contents(self):
231 """Make sure the element's contents aren't bogus."""
232 for element in self.contents.values():
233 if element.get("location") != self.key:
234 del self.contents[element.key]
236 def go_to(self, area):
237 """Relocate the element to a specific area."""
238 current = self.get("location")
239 if current and self.key in self.universe.contents[current].contents:
240 del universe.contents[current].contents[self.key]
241 if area in self.universe.contents:
242 self.set("location", area)
243 self.universe.contents[area].contents[self.key] = self
247 """Relocate the element to its default location."""
248 self.go_to(self.get("default_location"))
249 self.echo_to_location(
250 "You suddenly realize that " + self.get("name") + " is here."
253 def move_direction(self, direction):
254 """Relocate the element in a specified direction."""
255 self.echo_to_location(
258 ) + " exits " + self.universe.categories[
269 "You exit " + self.universe.categories[
281 self.universe.contents[
282 self.get("location")].link_neighbor(direction)
284 self.echo_to_location(
287 ) + " arrives from " + self.universe.categories[
298 def look_at(self, key):
299 """Show an element to another element."""
301 element = self.universe.contents[key]
303 name = element.get("name")
305 message += "$(cyn)" + name + "$(nrm)$(eol)"
306 description = element.get("description")
308 message += description + "$(eol)"
309 portal_list = list(element.portals().keys())
312 message += "$(cyn)[ Exits: " + ", ".join(
315 for element in self.universe.contents[
318 if element.get("is_actor") and element is not self:
319 message += "$(yel)" + element.get(
321 ) + " is here.$(nrm)$(eol)"
322 elif element is not self:
323 message += "$(grn)" + element.get(
329 """Map the portal directions for an area to neighbors."""
331 if re.match("""^area:-?\d+,-?\d+,-?\d+$""", self.key):
332 coordinates = [(int(x))
333 for x in self.key.split(":")[1].split(",")]
334 directions = self.universe.categories["internal"]["directions"]
338 x, directions.get(x)["vector"]
339 ) for x in directions.facets()
342 for portal in self.get("gridlinks"):
343 adjacent = map(lambda c, o: c + o,
344 coordinates, offsets[portal])
345 neighbor = "area:" + ",".join(
346 [(str(x)) for x in adjacent]
348 if neighbor in self.universe.contents:
349 portals[portal] = neighbor
350 for facet in self.facets():
351 if facet.startswith("link_"):
352 neighbor = self.get(facet)
353 if neighbor in self.universe.contents:
354 portal = facet.split("_")[1]
355 portals[portal] = neighbor
358 def link_neighbor(self, direction):
359 """Return the element linked in a given direction."""
360 portals = self.portals()
361 if direction in portals:
362 return portals[direction]
364 def echo_to_location(self, message):
365 """Show a message to other elements in the current location."""
366 for element in self.universe.contents[
369 if element is not self:
370 element.send(message)
377 def __init__(self, filename="", load=False):
378 """Initialize the universe."""
381 self.default_origins = {}
383 self.private_files = []
384 self.reload_flag = False
385 self.setup_loglines = []
386 self.startdir = os.getcwd()
387 self.terminate_flag = False
390 possible_filenames = [
392 "/usr/local/mudpy/etc/mudpy.yaml",
393 "/usr/local/etc/mudpy.yaml",
394 "/etc/mudpy/mudpy.yaml",
397 for filename in possible_filenames:
398 if os.access(filename, os.R_OK):
400 if not os.path.isabs(filename):
401 filename = os.path.join(self.startdir, filename)
402 self.filename = filename
404 # make sure to preserve any accumulated log entries during load
405 self.setup_loglines += self.load()
408 """Load universe data from persistent storage."""
410 # it's possible for this to enter before logging configuration is read
411 pending_loglines = []
413 # the files dict must exist and filename needs to be read-only
417 self.filename in self.files and self.files[
422 # clear out all read-only files
423 if hasattr(self, "files"):
424 for data_filename in list(self.files.keys()):
425 if not self.files[data_filename].is_writeable():
426 del self.files[data_filename]
428 # start loading from the initial file
429 mudpy.data.DataFile(self.filename, self)
431 # make a list of inactive avatars
432 inactive_avatars = []
433 for account in self.categories["account"].values():
434 for avatar in account.get("avatars"):
436 inactive_avatars.append(self.contents[avatar])
438 pending_loglines.append((
439 "Missing avatar \"%s\", possible data corruption" %
441 for user in self.userlist:
442 if user.avatar in inactive_avatars:
443 inactive_avatars.remove(user.avatar)
445 # go through all elements to clear out inactive avatar locations
446 for element in self.contents.values():
447 area = element.get("location")
448 if element in inactive_avatars and area:
449 if area in self.contents and element.key in self.contents[
452 del self.contents[area].contents[element.key]
453 element.set("default_location", area)
454 element.remove_facet("location")
456 # another pass to straighten out all the element contents
457 for element in self.contents.values():
458 element.update_location()
459 element.clean_contents()
460 return pending_loglines
463 """Create a new, empty Universe (the Big Bang)."""
464 new_universe = Universe()
465 for attribute in vars(self).keys():
466 exec("new_universe." + attribute + " = self." + attribute)
467 new_universe.reload_flag = False
472 """Save the universe to persistent storage."""
473 for key in self.files:
474 self.files[key].save()
476 def initialize_server_socket(self):
477 """Create and open the listening socket."""
479 # need to know the local address and port number for the listener
480 host = self.categories["internal"]["network"].get("host")
481 port = self.categories["internal"]["network"].get("port")
483 # if no host was specified, bind to all local addresses (preferring
491 # figure out if this is ipv4 or v6
492 family = socket.getaddrinfo(host, port)[0][0]
493 if family is socket.AF_INET6 and not socket.has_ipv6:
494 log("No support for IPv6 address %s (use IPv4 instead)." % host)
496 # create a new stream-type socket object
497 self.listening_socket = socket.socket(family, socket.SOCK_STREAM)
499 # set the socket options to allow existing open ones to be
500 # reused (fixes a bug where the server can't bind for a minute
501 # when restarting on linux systems)
502 self.listening_socket.setsockopt(
503 socket.SOL_SOCKET, socket.SO_REUSEADDR, 1
506 # bind the socket to to our desired server ipa and port
507 self.listening_socket.bind((host, port))
509 # disable blocking so we can proceed whether or not we can
511 self.listening_socket.setblocking(0)
513 # start listening on the socket
514 self.listening_socket.listen(1)
516 # note that we're now ready for user connections
518 "Listening for Telnet connections on: " +
519 host + ":" + str(port)
523 """Convenience method to get the elapsed time counter."""
524 return self.categories["internal"]["counters"].get("elapsed")
529 """This is a connected user."""
532 """Default values for the in-memory user variables."""
535 self.authenticated = False
538 self.connection = None
540 self.input_queue = []
541 self.last_address = ""
542 self.last_input = universe.get_time()
543 self.menu_choices = {}
544 self.menu_seen = False
545 self.negotiation_pause = 0
546 self.output_queue = []
547 self.partial_input = b""
548 self.password_tries = 0
549 self.state = "initial"
553 """Log, close the connection and remove."""
555 name = self.account.get("name")
559 message = "User " + name
561 message = "An unnamed user"
562 message += " logged out."
564 self.deactivate_avatar()
565 self.connection.close()
568 def check_idle(self):
569 """Warn or disconnect idle users as appropriate."""
570 idletime = universe.get_time() - self.last_input
571 linkdead_dict = universe.categories["internal"]["time"].get(
574 if self.state in linkdead_dict:
575 linkdead_state = self.state
577 linkdead_state = "default"
578 if idletime > linkdead_dict[linkdead_state]:
580 "$(eol)$(red)You've done nothing for far too long... goodbye!"
585 logline = "Disconnecting "
586 if self.account and self.account.get("name"):
587 logline += self.account.get("name")
589 logline += "an unknown user"
590 logline += (" after idling too long in the " + self.state
593 self.state = "disconnecting"
594 self.menu_seen = False
595 idle_dict = universe.categories["internal"]["time"].get("idle")
596 if self.state in idle_dict:
597 idle_state = self.state
599 idle_state = "default"
600 if idletime == idle_dict[idle_state]:
602 "$(eol)$(red)If you continue to be unproductive, "
603 + "you'll be shown the door...$(nrm)$(eol)"
607 """Save, load a new user and relocate the connection."""
609 # get out of the list
612 # create a new user object
615 # set everything equivalent
616 for attribute in vars(self).keys():
617 exec("new_user." + attribute + " = self." + attribute)
619 # the avatar needs a new owner
621 new_user.avatar.owner = new_user
624 universe.userlist.append(new_user)
626 # get rid of the old user object
629 def replace_old_connections(self):
630 """Disconnect active users with the same name."""
632 # the default return value
635 # iterate over each user in the list
636 for old_user in universe.userlist:
638 # the name is the same but it's not us
641 ) and old_user.account and old_user.account.get(
643 ) == self.account.get(
645 ) and old_user is not self:
649 "User " + self.account.get(
651 ) + " reconnected--closing old connection to "
652 + old_user.address + ".",
656 "$(eol)$(red)New connection from " + self.address
657 + ". Terminating old connection...$(nrm)$(eol)",
662 # close the old connection
663 old_user.connection.close()
665 # replace the old connection with this one
667 "$(eol)$(red)Taking over old connection from "
668 + old_user.address + ".$(nrm)"
670 old_user.connection = self.connection
671 old_user.last_address = old_user.address
672 old_user.address = self.address
674 # take this one out of the list and delete
680 # true if an old connection was replaced, false if not
683 def authenticate(self):
684 """Flag the user as authenticated and disconnect duplicates."""
685 if self.state is not "authenticated":
686 log("User " + self.account.get("name") + " logged in.", 2)
687 self.authenticated = True
688 if self.account.subkey in universe.contents["mudpy.limit"].get(
690 self.account.set("administrator", "True")
693 """Send the user their current menu."""
694 if not self.menu_seen:
695 self.menu_choices = get_menu_choices(self)
697 get_menu(self.state, self.error, self.menu_choices),
701 self.menu_seen = True
703 self.adjust_echoing()
705 def adjust_echoing(self):
706 """Adjust echoing to match state menu requirements."""
707 if mudpy.telnet.is_enabled(self, mudpy.telnet.TELOPT_ECHO,
709 if menu_echo_on(self.state):
710 mudpy.telnet.disable(self, mudpy.telnet.TELOPT_ECHO,
712 elif not menu_echo_on(self.state):
713 mudpy.telnet.enable(self, mudpy.telnet.TELOPT_ECHO,
717 """Remove a user from the list of connected users."""
718 universe.userlist.remove(self)
728 add_terminator=False,
731 """Send arbitrary text to a connected user."""
733 # unless raw mode is on, clean it up all nice and pretty
736 # strip extra $(eol) off if present
737 while output.startswith("$(eol)"):
739 while output.endswith("$(eol)"):
741 extra_lines = output.find("$(eol)$(eol)$(eol)")
742 while extra_lines > -1:
743 output = output[:extra_lines] + output[extra_lines + 6:]
744 extra_lines = output.find("$(eol)$(eol)$(eol)")
746 # start with a newline, append the message, then end
747 # with the optional eol string passed to this function
748 # and the ansi escape to return to normal text
749 if not just_prompt and prepend_padding:
750 if (not self.output_queue or not
751 self.output_queue[-1].endswith(b"\r\n")):
752 output = "$(eol)" + output
753 elif not self.output_queue[-1].endswith(
755 ) and not self.output_queue[-1].endswith(
758 output = "$(eol)" + output
759 output += eol + chr(27) + "[0m"
761 # tack on a prompt if active
762 if self.state == "active":
767 mode = self.avatar.get("mode")
769 output += "(" + mode + ") "
771 # find and replace macros in the output
772 output = replace_macros(self, output)
774 # wrap the text at the client's width (min 40, 0 disables)
776 if self.columns < 40:
780 output = wrap_ansi_text(output, wrap)
782 # if supported by the client, encode it utf-8
783 if mudpy.telnet.is_enabled(self, mudpy.telnet.TELOPT_BINARY,
785 encoded_output = output.encode("utf-8")
787 # otherwise just send ascii
789 encoded_output = output.encode("ascii", "replace")
791 # end with a terminator if requested
792 if add_prompt or add_terminator:
793 if mudpy.telnet.is_enabled(
794 self, mudpy.telnet.TELOPT_EOR, mudpy.telnet.US):
795 encoded_output += mudpy.telnet.telnet_proto(
796 mudpy.telnet.IAC, mudpy.telnet.EOR)
797 elif not mudpy.telnet.is_enabled(
798 self, mudpy.telnet.TELOPT_SGA, mudpy.telnet.US):
799 encoded_output += mudpy.telnet.telnet_proto(
800 mudpy.telnet.IAC, mudpy.telnet.GA)
802 # and tack it onto the queue
803 self.output_queue.append(encoded_output)
805 # if this is urgent, flush all pending output
809 # just dump raw bytes as requested
811 self.output_queue.append(output)
815 """All the things to do to the user per increment."""
817 # if the world is terminating, disconnect
818 if universe.terminate_flag:
819 self.state = "disconnecting"
820 self.menu_seen = False
822 # check for an idle connection and act appropriately
826 # if output is paused, decrement the counter
827 if self.state == "initial":
828 if self.negotiation_pause:
829 self.negotiation_pause -= 1
831 self.state = "entering_account_name"
833 # show the user a menu as needed
834 elif not self.state == "active":
837 # flush any pending output in the queue
840 # disconnect users with the appropriate state
841 if self.state == "disconnecting":
844 # check for input and add it to the queue
847 # there is input waiting in the queue
849 handle_user_input(self)
852 """Try to send the last item in the queue and remove it."""
853 if self.output_queue:
855 self.connection.send(self.output_queue[0])
856 except BrokenPipeError:
857 if self.account and self.account.get("name"):
858 account = self.account.get("name")
860 account = "an unknown user"
861 self.state = "disconnecting"
862 log("Broken pipe sending to %s." % account, 7)
863 del self.output_queue[0]
865 def enqueue_input(self):
866 """Process and enqueue any new input."""
868 # check for some input
870 raw_input = self.connection.recv(1024)
871 except (BlockingIOError, OSError):
877 # tack this on to any previous partial
878 self.partial_input += raw_input
880 # reply to and remove any IAC negotiation codes
881 mudpy.telnet.negotiate_telnet_options(self)
883 # separate multiple input lines
884 new_input_lines = self.partial_input.split(b"\n")
886 # if input doesn't end in a newline, replace the
887 # held partial input with the last line of it
888 if not self.partial_input.endswith(b"\n"):
889 self.partial_input = new_input_lines.pop()
891 # otherwise, chop off the extra null input and reset
892 # the held partial input
894 new_input_lines.pop()
895 self.partial_input = b""
897 # iterate over the remaining lines
898 for line in new_input_lines:
900 # strip off extra whitespace
903 # log non-printable characters remaining
904 if mudpy.telnet.is_enabled(self, mudpy.telnet.TELOPT_BINARY,
906 asciiline = bytes([x for x in line if 32 <= x <= 126])
907 if line != asciiline:
908 logline = "Non-ASCII characters from "
909 if self.account and self.account.get("name"):
910 logline += self.account.get("name") + ": "
912 logline += "unknown user: "
913 logline += repr(line)
918 line = line.decode("utf-8")
919 except UnicodeDecodeError:
920 logline = "Non-UTF-8 characters from "
921 if self.account and self.account.get("name"):
922 logline += self.account.get("name") + ": "
924 logline += "unknown user: "
925 logline += repr(line)
929 line = unicodedata.normalize("NFKC", line)
931 # put on the end of the queue
932 self.input_queue.append(line)
934 def new_avatar(self):
935 """Instantiate a new, unconfigured avatar for this user."""
937 while "avatar:" + self.account.get("name") + ":" + str(
939 ) in universe.categories["actor"].keys():
941 self.avatar = Element(
942 "actor:avatar:" + self.account.get("name") + ":" + str(
945 universe, old_style=True
947 self.avatar.append("inherit", "archetype:avatar")
948 self.account.append("avatars", self.avatar.key)
950 def delete_avatar(self, avatar):
951 """Remove an avatar from the world and from the user's list."""
952 if self.avatar is universe.contents[avatar]:
954 universe.contents[avatar].destroy()
955 avatars = self.account.get("avatars")
956 avatars.remove(avatar)
957 self.account.set("avatars", avatars)
959 def activate_avatar_by_index(self, index):
960 """Enter the world with a particular indexed avatar."""
961 self.avatar = universe.contents[
962 self.account.get("avatars")[index]]
963 self.avatar.owner = self
964 self.state = "active"
965 self.avatar.go_home()
967 def deactivate_avatar(self):
968 """Have the active avatar leave the world."""
970 current = self.avatar.get("location")
972 self.avatar.set("default_location", current)
973 self.avatar.echo_to_location(
974 "You suddenly wonder where " + self.avatar.get(
978 del universe.contents[current].contents[self.avatar.key]
979 self.avatar.remove_facet("location")
980 self.avatar.owner = None
984 """Destroy the user and associated avatars."""
985 for avatar in self.account.get("avatars"):
986 self.delete_avatar(avatar)
987 self.account.destroy()
989 def list_avatar_names(self):
990 """List names of assigned avatars."""
992 for avatar in self.account.get("avatars"):
994 avatars.append(universe.contents[avatar].get("name"))
996 log("Missing avatar \"%s\", possible data corruption." %
1001 def broadcast(message, add_prompt=True):
1002 """Send a message to all connected users."""
1003 for each_user in universe.userlist:
1004 each_user.send("$(eol)" + message, add_prompt=add_prompt)
1007 def log(message, level=0):
1008 """Log a message."""
1010 # a couple references we need
1011 file_name = universe.contents["mudpy.log"].get("file")
1012 max_log_lines = universe.contents["mudpy.log"].get("lines")
1013 syslog_name = universe.contents["mudpy.log"].get("syslog")
1014 timestamp = time.asctime()[4:19]
1016 # turn the message into a list of nonempty lines
1017 lines = [x for x in [(x.rstrip()) for x in message.split("\n")] if x != ""]
1019 # send the timestamp and line to a file
1021 if not os.path.isabs(file_name):
1022 file_name = os.path.join(universe.startdir, file_name)
1023 file_descriptor = codecs.open(file_name, "a", "utf-8")
1025 file_descriptor.write(timestamp + " " + line + "\n")
1026 file_descriptor.flush()
1027 file_descriptor.close()
1029 # send the timestamp and line to standard output
1030 if universe.contents["mudpy.log"].get("stdout"):
1032 print(timestamp + " " + line)
1034 # send the line to the system log
1037 syslog_name.encode("utf-8"),
1039 syslog.LOG_INFO | syslog.LOG_DAEMON
1045 # display to connected administrators
1046 for user in universe.userlist:
1047 if user.state == "active" and user.account.get(
1049 ) and user.account.get("loglevel", 0) <= level:
1050 # iterate over every line in the message
1054 "$(bld)$(red)" + timestamp + " "
1055 + line.replace("$(", "$_(") + "$(nrm)$(eol)")
1056 user.send(full_message, flush=True)
1058 # add to the recent log list
1060 while 0 < len(universe.loglines) >= max_log_lines:
1061 del universe.loglines[0]
1062 universe.loglines.append((level, timestamp + " " + line))
1065 def get_loglines(level, start, stop):
1066 """Return a specific range of loglines filtered by level."""
1068 # filter the log lines
1069 loglines = [x for x in universe.loglines if x[0] >= level]
1071 # we need these in several places
1072 total_count = str(len(universe.loglines))
1073 filtered_count = len(loglines)
1075 # don't proceed if there are no lines
1078 # can't start before the begining or at the end
1079 if start > filtered_count:
1080 start = filtered_count
1084 # can't stop before we start
1091 message = "There are " + str(total_count)
1092 message += " log lines in memory and " + str(filtered_count)
1093 message += " at or above level " + str(level) + "."
1094 message += " The matching lines from " + str(stop) + " to "
1095 message += str(start) + " are:$(eol)$(eol)"
1097 # add the text from the selected lines
1099 range_lines = loglines[-start:-(stop - 1)]
1101 range_lines = loglines[-start:]
1102 for line in range_lines:
1103 message += " (" + str(line[0]) + ") " + line[1].replace(
1107 # there were no lines
1109 message = "None of the " + str(total_count)
1110 message += " lines in memory matches your request."
1116 def glyph_columns(character):
1117 """Convenience function to return the column width of a glyph."""
1118 if unicodedata.east_asian_width(character) in "FW":
1124 def wrap_ansi_text(text, width):
1125 """Wrap text with arbitrary width while ignoring ANSI colors."""
1127 # the current position in the entire text string, including all
1128 # characters, printable or otherwise
1131 # the current text position relative to the begining of the line,
1132 # ignoring color escape sequences
1135 # the absolute position of the most recent whitespace character
1138 # whether the current character is part of a color escape sequence
1141 # normalize any potentially composited unicode before we count it
1142 text = unicodedata.normalize("NFKC", text)
1144 # iterate over each character from the begining of the text
1145 for each_character in text:
1147 # the current character is the escape character
1148 if each_character == "\x1b" and not escape:
1151 # the current character is within an escape sequence
1154 # the current character is m, which terminates the
1156 if each_character == "m":
1159 # the current character is a newline, so reset the relative
1160 # position (start a new line)
1161 elif each_character == "\n":
1163 last_whitespace = abs_pos
1165 # the current character meets the requested maximum line width,
1166 # so we need to backtrack and find a space at which to wrap;
1167 # special care is taken to avoid an off-by-one in case the
1168 # current character is a double-width glyph
1169 elif each_character != "\r" and (
1170 rel_pos >= width or (
1171 rel_pos >= width - 1 and glyph_columns(
1177 # it's always possible we landed on whitespace
1178 if unicodedata.category(each_character) in ("Cc", "Zs"):
1179 last_whitespace = abs_pos
1181 # insert an eol in place of the space
1182 text = text[:last_whitespace] + "\r\n" + text[last_whitespace + 1:]
1184 # increase the absolute position because an eol is two
1185 # characters but the space it replaced was only one
1188 # now we're at the begining of a new line, plus the
1189 # number of characters wrapped from the previous line
1191 for remaining_characters in text[last_whitespace:abs_pos]:
1192 rel_pos += glyph_columns(remaining_characters)
1194 # as long as the character is not a carriage return and the
1195 # other above conditions haven't been met, count it as a
1196 # printable character
1197 elif each_character != "\r":
1198 rel_pos += glyph_columns(each_character)
1199 if unicodedata.category(each_character) in ("Cc", "Zs"):
1200 last_whitespace = abs_pos
1202 # increase the absolute position for every character
1205 # return the newly-wrapped text
1209 def weighted_choice(data):
1210 """Takes a dict weighted by value and returns a random key."""
1212 # this will hold our expanded list of keys from the data
1215 # create the expanded list of keys
1216 for key in data.keys():
1217 for count in range(data[key]):
1218 expanded.append(key)
1220 # return one at random
1221 return random.choice(expanded)
1225 """Returns a random character name."""
1227 # the vowels and consonants needed to create romaji syllables
1256 # this dict will hold our weighted list of syllables
1259 # generate the list with an even weighting
1260 for consonant in consonants:
1261 for vowel in vowels:
1262 syllables[consonant + vowel] = 1
1264 # we'll build the name into this string
1267 # create a name of random length from the syllables
1268 for syllable in range(random.randrange(2, 6)):
1269 name += weighted_choice(syllables)
1271 # strip any leading quotemark, capitalize and return the name
1272 return name.strip("'").capitalize()
1275 def replace_macros(user, text, is_input=False):
1276 """Replaces macros in text output."""
1278 # third person pronouns
1280 "female": {"obj": "her", "pos": "hers", "sub": "she"},
1281 "male": {"obj": "him", "pos": "his", "sub": "he"},
1282 "neuter": {"obj": "it", "pos": "its", "sub": "it"}
1285 # a dict of replacement macros
1288 "bld": chr(27) + "[1m",
1289 "nrm": chr(27) + "[0m",
1290 "blk": chr(27) + "[30m",
1291 "blu": chr(27) + "[34m",
1292 "cyn": chr(27) + "[36m",
1293 "grn": chr(27) + "[32m",
1294 "mgt": chr(27) + "[35m",
1295 "red": chr(27) + "[31m",
1296 "yel": chr(27) + "[33m",
1299 # add dynamic macros where possible
1301 account_name = user.account.get("name")
1303 macros["account"] = account_name
1305 avatar_gender = user.avatar.get("gender")
1307 macros["tpop"] = pronouns[avatar_gender]["obj"]
1308 macros["tppp"] = pronouns[avatar_gender]["pos"]
1309 macros["tpsp"] = pronouns[avatar_gender]["sub"]
1314 # find and replace per the macros dict
1315 macro_start = text.find("$(")
1316 if macro_start == -1:
1318 macro_end = text.find(")", macro_start) + 1
1319 macro = text[macro_start + 2:macro_end - 1]
1320 if macro in macros.keys():
1321 replacement = macros[macro]
1323 # this is how we handle local file inclusion (dangerous!)
1324 elif macro.startswith("inc:"):
1325 incfile = mudpy.data.find_file(macro[4:], universe=universe)
1326 if os.path.exists(incfile):
1327 incfd = codecs.open(incfile, "r", "utf-8")
1330 if line.endswith("\n") and not line.endswith("\r\n"):
1331 line = line.replace("\n", "\r\n")
1333 # lose the trailing eol
1334 replacement = replacement[:-2]
1337 log("Couldn't read included " + incfile + " file.", 6)
1339 # if we get here, log and replace it with null
1343 log("Unexpected replacement macro " +
1344 macro + " encountered.", 6)
1346 # and now we act on the replacement
1347 text = text.replace("$(" + macro + ")", replacement)
1349 # replace the look-like-a-macro sequence
1350 text = text.replace("$_(", "$(")
1355 def escape_macros(value):
1356 """Escapes replacement macros in text."""
1357 if type(value) is str:
1358 return value.replace("$(", "$_(")
1363 def first_word(text, separator=" "):
1364 """Returns a tuple of the first word and the rest."""
1366 if text.find(separator) > 0:
1367 return text.split(separator, 1)
1375 """The things which should happen on each pulse, aside from reloads."""
1377 # open the listening socket if it hasn't been already
1378 if not hasattr(universe, "listening_socket"):
1379 universe.initialize_server_socket()
1381 # assign a user if a new connection is waiting
1382 user = check_for_connection(universe.listening_socket)
1384 universe.userlist.append(user)
1386 # iterate over the connected users
1387 for user in universe.userlist:
1390 # add an element for counters if it doesn't exist
1391 if "counters" not in universe.categories["internal"]:
1392 universe.categories["internal"]["counters"] = Element(
1393 "internal:counters", universe, old_style=True
1396 # update the log every now and then
1397 if not universe.categories["internal"]["counters"].get("mark"):
1398 log(str(len(universe.userlist)) + " connection(s)")
1399 universe.categories["internal"]["counters"].set(
1400 "mark", universe.categories["internal"]["time"].get(
1405 universe.categories["internal"]["counters"].set(
1406 "mark", universe.categories["internal"]["counters"].get(
1411 # periodically save everything
1412 if not universe.categories["internal"]["counters"].get("save"):
1414 universe.categories["internal"]["counters"].set(
1415 "save", universe.categories["internal"]["time"].get(
1420 universe.categories["internal"]["counters"].set(
1421 "save", universe.categories["internal"]["counters"].get(
1426 # pause for a configurable amount of time (decimal seconds)
1427 time.sleep(universe.categories["internal"]
1428 ["time"].get("increment"))
1430 # increase the elapsed increment counter
1431 universe.categories["internal"]["counters"].set(
1432 "elapsed", universe.categories["internal"]["counters"].get(
1439 """Reload all relevant objects."""
1440 for user in universe.userlist[:]:
1442 for element in universe.contents.values():
1443 if element.origin.is_writeable():
1448 def check_for_connection(listening_socket):
1449 """Check for a waiting connection and return a new user object."""
1451 # try to accept a new connection
1453 connection, address = listening_socket.accept()
1454 except BlockingIOError:
1457 # note that we got one
1458 log("Connection from " + address[0], 2)
1460 # disable blocking so we can proceed whether or not we can send/receive
1461 connection.setblocking(0)
1463 # create a new user object
1466 # associate this connection with it
1467 user.connection = connection
1469 # set the user's ipa from the connection's ipa
1470 user.address = address[0]
1472 # let the client know we WILL EOR (RFC 885)
1473 mudpy.telnet.enable(user, mudpy.telnet.TELOPT_EOR, mudpy.telnet.US)
1474 user.negotiation_pause = 2
1476 # return the new user object
1480 def get_menu(state, error=None, choices=None):
1481 """Show the correct menu text to a user."""
1483 # make sure we don't reuse a mutable sequence by default
1487 # get the description or error text
1488 message = get_menu_description(state, error)
1490 # get menu choices for the current state
1491 message += get_formatted_menu_choices(state, choices)
1493 # try to get a prompt, if it was defined
1494 message += get_menu_prompt(state)
1496 # throw in the default choice, if it exists
1497 message += get_formatted_default_menu_choice(state)
1499 # display a message indicating if echo is off
1500 message += get_echo_message(state)
1502 # return the assembly of various strings defined above
1506 def menu_echo_on(state):
1507 """True if echo is on, false if it is off."""
1508 return universe.categories["menu"][state].get("echo", True)
1511 def get_echo_message(state):
1512 """Return a message indicating that echo is off."""
1513 if menu_echo_on(state):
1516 return "(won't echo) "
1519 def get_default_menu_choice(state):
1520 """Return the default choice for a menu."""
1521 return universe.categories["menu"][state].get("default")
1524 def get_formatted_default_menu_choice(state):
1525 """Default menu choice foratted for inclusion in a prompt string."""
1526 default_choice = get_default_menu_choice(state)
1528 return "[$(red)" + default_choice + "$(nrm)] "
1533 def get_menu_description(state, error):
1534 """Get the description or error text."""
1536 # an error condition was raised by the handler
1539 # try to get an error message matching the condition
1541 description = universe.categories[
1542 "menu"][state].get("error_" + error)
1544 description = "That is not a valid choice..."
1545 description = "$(red)" + description + "$(nrm)"
1547 # there was no error condition
1550 # try to get a menu description for the current state
1551 description = universe.categories["menu"][state].get("description")
1553 # return the description or error message
1555 description += "$(eol)$(eol)"
1559 def get_menu_prompt(state):
1560 """Try to get a prompt, if it was defined."""
1561 prompt = universe.categories["menu"][state].get("prompt")
1567 def get_menu_choices(user):
1568 """Return a dict of choice:meaning."""
1569 menu = universe.categories["menu"][user.state]
1570 create_choices = menu.get("create")
1572 choices = eval(create_choices)
1578 for facet in menu.facets():
1579 if facet.startswith("demand_") and not eval(
1580 universe.categories["menu"][user.state].get(facet)
1582 ignores.append(facet.split("_", 2)[1])
1583 elif facet.startswith("create_"):
1584 creates[facet] = facet.split("_", 2)[1]
1585 elif facet.startswith("choice_"):
1586 options[facet] = facet.split("_", 2)[1]
1587 for facet in creates.keys():
1588 if not creates[facet] in ignores:
1589 choices[creates[facet]] = eval(menu.get(facet))
1590 for facet in options.keys():
1591 if not options[facet] in ignores:
1592 choices[options[facet]] = menu.get(facet)
1596 def get_formatted_menu_choices(state, choices):
1597 """Returns a formatted string of menu choices."""
1599 choice_keys = list(choices.keys())
1601 for choice in choice_keys:
1602 choice_output += " [$(red)" + choice + "$(nrm)] " + choices[
1606 choice_output += "$(eol)"
1607 return choice_output
1610 def get_menu_branches(state):
1611 """Return a dict of choice:branch."""
1613 for facet in universe.categories["menu"][state].facets():
1614 if facet.startswith("branch_"):
1616 facet.split("_", 2)[1]
1617 ] = universe.categories["menu"][state].get(facet)
1621 def get_default_branch(state):
1622 """Return the default branch."""
1623 return universe.categories["menu"][state].get("branch")
1626 def get_choice_branch(user, choice):
1627 """Returns the new state matching the given choice."""
1628 branches = get_menu_branches(user.state)
1629 if choice in branches.keys():
1630 return branches[choice]
1631 elif choice in user.menu_choices.keys():
1632 return get_default_branch(user.state)
1637 def get_menu_actions(state):
1638 """Return a dict of choice:branch."""
1640 for facet in universe.categories["menu"][state].facets():
1641 if facet.startswith("action_"):
1643 facet.split("_", 2)[1]
1644 ] = universe.categories["menu"][state].get(facet)
1648 def get_default_action(state):
1649 """Return the default action."""
1650 return universe.categories["menu"][state].get("action")
1653 def get_choice_action(user, choice):
1654 """Run any indicated script for the given choice."""
1655 actions = get_menu_actions(user.state)
1656 if choice in actions.keys():
1657 return actions[choice]
1658 elif choice in user.menu_choices.keys():
1659 return get_default_action(user.state)
1664 def handle_user_input(user):
1665 """The main handler, branches to a state-specific handler."""
1667 # if the user's client echo is off, send a blank line for aesthetics
1668 if mudpy.telnet.is_enabled(user, mudpy.telnet.TELOPT_ECHO,
1670 user.send("", add_prompt=False, prepend_padding=False)
1672 # check to make sure the state is expected, then call that handler
1673 if "handler_" + user.state in globals():
1674 exec("handler_" + user.state + "(user)")
1676 generic_menu_handler(user)
1678 # since we got input, flag that the menu/prompt needs to be redisplayed
1679 user.menu_seen = False
1681 # update the last_input timestamp while we're at it
1682 user.last_input = universe.get_time()
1685 def generic_menu_handler(user):
1686 """A generic menu choice handler."""
1688 # get a lower-case representation of the next line of input
1689 if user.input_queue:
1690 choice = user.input_queue.pop(0)
1692 choice = choice.lower()
1696 choice = get_default_menu_choice(user.state)
1697 if choice in user.menu_choices:
1698 exec(get_choice_action(user, choice))
1699 new_state = get_choice_branch(user, choice)
1701 user.state = new_state
1703 user.error = "default"
1706 def handler_entering_account_name(user):
1707 """Handle the login account name."""
1709 # get the next waiting line of input
1710 input_data = user.input_queue.pop(0)
1712 # did the user enter anything?
1715 # keep only the first word and convert to lower-case
1716 name = input_data.lower()
1718 # fail if there are non-alphanumeric characters
1719 if name != "".join(filter(
1720 lambda x: x >= "0" and x <= "9" or x >= "a" and x <= "z",
1722 user.error = "bad_name"
1724 # if that account exists, time to request a password
1725 elif name in universe.categories["account"]:
1726 user.account = universe.categories["account"][name]
1727 user.state = "checking_password"
1729 # otherwise, this could be a brand new user
1731 user.account = Element("account:" + name, universe, old_style=True)
1732 user.account.set("name", name)
1733 log("New user: " + name, 2)
1734 user.state = "checking_new_account_name"
1736 # if the user entered nothing for a name, then buhbye
1738 user.state = "disconnecting"
1741 def handler_checking_password(user):
1742 """Handle the login account password."""
1744 # get the next waiting line of input
1745 input_data = user.input_queue.pop(0)
1747 # does the hashed input equal the stored hash?
1748 if mudpy.password.verify(input_data, user.account.get("passhash")):
1750 # if so, set the username and load from cold storage
1751 if not user.replace_old_connections():
1753 user.state = "main_utility"
1755 # if at first your hashes don't match, try, try again
1756 elif user.password_tries < universe.contents["mudpy.limit"].get(
1757 "password_tries") - 1:
1758 user.password_tries += 1
1759 user.error = "incorrect"
1761 # we've exceeded the maximum number of password failures, so disconnect
1764 "$(eol)$(red)Too many failed password attempts...$(nrm)$(eol)"
1766 user.state = "disconnecting"
1769 def handler_entering_new_password(user):
1770 """Handle a new password entry."""
1772 # get the next waiting line of input
1773 input_data = user.input_queue.pop(0)
1775 # make sure the password is strong--at least one upper, one lower and
1776 # one digit, seven or more characters in length
1777 if len(input_data) > 6 and len(
1778 list(filter(lambda x: x >= "0" and x <= "9", input_data))
1780 list(filter(lambda x: x >= "A" and x <= "Z", input_data))
1782 list(filter(lambda x: x >= "a" and x <= "z", input_data))
1785 # hash and store it, then move on to verification
1786 user.account.set("passhash", mudpy.password.create(input_data))
1787 user.state = "verifying_new_password"
1789 # the password was weak, try again if you haven't tried too many times
1790 elif user.password_tries < universe.contents["mudpy.limit"].get(
1791 "password_tries") - 1:
1792 user.password_tries += 1
1795 # too many tries, so adios
1798 "$(eol)$(red)Too many failed password attempts...$(nrm)$(eol)"
1800 user.account.destroy()
1801 user.state = "disconnecting"
1804 def handler_verifying_new_password(user):
1805 """Handle the re-entered new password for verification."""
1807 # get the next waiting line of input
1808 input_data = user.input_queue.pop(0)
1810 # hash the input and match it to storage
1811 if mudpy.password.verify(input_data, user.account.get("passhash")):
1814 # the hashes matched, so go active
1815 if not user.replace_old_connections():
1816 user.state = "main_utility"
1818 # go back to entering the new password as long as you haven't tried
1820 elif user.password_tries < universe.contents["mudpy.limit"].get(
1821 "password_tries") - 1:
1822 user.password_tries += 1
1823 user.error = "differs"
1824 user.state = "entering_new_password"
1826 # otherwise, sayonara
1829 "$(eol)$(red)Too many failed password attempts...$(nrm)$(eol)"
1831 user.account.destroy()
1832 user.state = "disconnecting"
1835 def handler_active(user):
1836 """Handle input for active users."""
1838 # get the next waiting line of input
1839 input_data = user.input_queue.pop(0)
1844 # split out the command and parameters
1846 mode = actor.get("mode")
1847 if mode and input_data.startswith("!"):
1848 command_name, parameters = first_word(input_data[1:])
1849 elif mode == "chat":
1850 command_name = "say"
1851 parameters = input_data
1853 command_name, parameters = first_word(input_data)
1855 # lowercase the command
1856 command_name = command_name.lower()
1858 # the command matches a command word for which we have data
1859 if command_name in universe.categories["command"]:
1860 command = universe.categories["command"][command_name]
1864 # if it's allowed, do it
1865 if actor.can_run(command):
1866 exec(command.get("action"))
1868 # otherwise, give an error
1870 command_error(actor, input_data)
1872 # if no input, just idle back with a prompt
1874 user.send("", just_prompt=True)
1877 def command_halt(actor, parameters):
1878 """Halt the world."""
1881 # see if there's a message or use a generic one
1883 message = "Halting: " + parameters
1885 message = "User " + actor.owner.account.get(
1887 ) + " halted the world."
1890 broadcast(message, add_prompt=False)
1893 # set a flag to terminate the world
1894 universe.terminate_flag = True
1897 def command_reload(actor):
1898 """Reload all code modules, configs and data."""
1901 # let the user know and log
1902 actor.send("Reloading all code modules, configs and data.")
1905 actor.owner.account.get("name") + " reloaded the world.",
1909 # set a flag to reload
1910 universe.reload_flag = True
1913 def command_quit(actor):
1914 """Leave the world and go back to the main menu."""
1916 actor.owner.state = "main_utility"
1917 actor.owner.deactivate_avatar()
1920 def command_help(actor, parameters):
1921 """List available commands and provide help for commands."""
1923 # did the user ask for help on a specific command word?
1924 if parameters and actor.owner:
1926 # is the command word one for which we have data?
1927 if parameters in universe.categories["command"]:
1928 command = universe.categories["command"][parameters]
1932 # only for allowed commands
1933 if actor.can_run(command):
1935 # add a description if provided
1936 description = command.get("description")
1938 description = "(no short description provided)"
1939 if command.get("administrative"):
1943 output += parameters + "$(nrm) - " + description + "$(eol)$(eol)"
1945 # add the help text if provided
1946 help_text = command.get("help")
1948 help_text = "No help is provided for this command."
1951 # list related commands
1952 see_also = command.get("see_also")
1954 really_see_also = ""
1955 for item in see_also:
1956 if item in universe.categories["command"]:
1957 command = universe.categories["command"][item]
1958 if actor.can_run(command):
1960 really_see_also += ", "
1961 if command.get("administrative"):
1962 really_see_also += "$(red)"
1964 really_see_also += "$(grn)"
1965 really_see_also += item + "$(nrm)"
1967 output += "$(eol)$(eol)See also: " + really_see_also
1969 # no data for the requested command word
1971 output = "That is not an available command."
1973 # no specific command word was indicated
1976 # give a sorted list of commands with descriptions if provided
1977 output = "These are the commands available to you:$(eol)$(eol)"
1978 sorted_commands = list(universe.categories["command"].keys())
1979 sorted_commands.sort()
1980 for item in sorted_commands:
1981 command = universe.categories["command"][item]
1982 if actor.can_run(command):
1983 description = command.get("description")
1985 description = "(no short description provided)"
1986 if command.get("administrative"):
1990 output += item + "$(nrm) - " + description + "$(eol)"
1991 output += ("$(eol)Enter \"help COMMAND\" for help on a command "
1992 "named \"COMMAND\".")
1994 # send the accumulated output to the user
1998 def command_move(actor, parameters):
1999 """Move the avatar in a given direction."""
2000 if parameters in universe.contents[actor.get("location")].portals():
2001 actor.move_direction(parameters)
2003 actor.send("You cannot go that way.")
2006 def command_look(actor, parameters):
2009 actor.send("You can't look at or in anything yet.")
2011 actor.look_at(actor.get("location"))
2014 def command_say(actor, parameters):
2015 """Speak to others in the same area."""
2017 # check for replacement macros and escape them
2018 parameters = escape_macros(parameters)
2020 # if the message is wrapped in quotes, remove them and leave contents
2022 if parameters.startswith("\"") and parameters.endswith("\""):
2023 message = parameters[1:-1]
2026 # otherwise, get rid of stray quote marks on the ends of the message
2028 message = parameters.strip("\"'`")
2031 # the user entered a message
2034 # match the punctuation used, if any, to an action
2035 actions = universe.contents["mudpy.linguistic"].get(
2038 default_punctuation = (
2039 universe.contents["mudpy.linguistic"].get(
2040 "default_punctuation"))
2043 # reverse sort punctuation options so the longest match wins
2044 for mark in sorted(actions.keys(), reverse=True):
2045 if not literal and message.endswith(mark):
2046 action = actions[mark]
2049 # add punctuation if needed
2051 action = actions[default_punctuation]
2052 if message and not (
2053 literal or unicodedata.category(message[-1]) == "Po"
2055 message += default_punctuation
2057 # failsafe checks to avoid unwanted reformatting and null strings
2058 if message and not literal:
2060 # decapitalize the first letter to improve matching
2061 message = message[0].lower() + message[1:]
2063 # iterate over all words in message, replacing typos
2064 typos = universe.contents["mudpy.linguistic"].get(
2067 words = message.split()
2068 for index in range(len(words)):
2070 while unicodedata.category(word[0]) == "Po":
2072 while unicodedata.category(word[-1]) == "Po":
2074 if word in typos.keys():
2075 words[index] = words[index].replace(word, typos[word])
2076 message = " ".join(words)
2078 # capitalize the first letter
2079 message = message[0].upper() + message[1:]
2083 actor.echo_to_location(
2084 actor.get("name") + " " + action + "s, \"" + message + "\""
2086 actor.send("You " + action + ", \"" + message + "\"")
2088 # there was no message
2090 actor.send("What do you want to say?")
2093 def command_chat(actor):
2094 """Toggle chat mode."""
2095 mode = actor.get("mode")
2097 actor.set("mode", "chat")
2098 actor.send("Entering chat mode (use $(grn)!chat$(nrm) to exit).")
2099 elif mode == "chat":
2100 actor.remove_facet("mode")
2101 actor.send("Exiting chat mode.")
2103 actor.send("Sorry, but you're already busy with something else!")
2106 def command_show(actor, parameters):
2107 """Show program data."""
2109 arguments = parameters.split()
2111 message = "What do you want to show?"
2112 elif arguments[0] == "time":
2113 message = universe.categories["internal"]["counters"].get(
2115 ) + " increments elapsed since the world was created."
2116 elif arguments[0] == "categories":
2117 message = "These are the element categories:$(eol)"
2118 categories = list(universe.categories.keys())
2120 for category in categories:
2121 message += "$(eol) $(grn)" + category + "$(nrm)"
2122 elif arguments[0] == "files":
2123 message = "These are the current files containing the universe:$(eol)"
2124 filenames = list(universe.files.keys())
2126 for filename in filenames:
2127 if universe.files[filename].is_writeable():
2131 message += ("$(eol) $(red)(" + status + ") $(grn)" + filename
2133 elif arguments[0] == "category":
2134 if len(arguments) != 2:
2135 message = "You must specify one category."
2136 elif arguments[1] in universe.categories:
2137 message = ("These are the elements in the \"" + arguments[1]
2138 + "\" category:$(eol)")
2141 universe.categories[arguments[1]][x].key
2142 ) for x in universe.categories[arguments[1]].keys()
2145 for element in elements:
2146 message += "$(eol) $(grn)" + element + "$(nrm)"
2148 message = "Category \"" + arguments[1] + "\" does not exist."
2149 elif arguments[0] == "file":
2150 if len(arguments) != 2:
2151 message = "You must specify one file."
2152 elif arguments[1] in universe.files:
2153 message = ("These are the elements in the \"" + arguments[1]
2155 elements = universe.files[arguments[1]].data.keys()
2157 for element in elements:
2158 message += "$(eol) $(grn)" + element + "$(nrm)"
2160 message = "Category \"" + arguments[1] + "\" does not exist."
2161 elif arguments[0] == "element":
2162 if len(arguments) != 2:
2163 message = "You must specify one element."
2164 elif arguments[1].strip(".") in universe.contents:
2165 element = universe.contents[arguments[1].strip(".")]
2166 message = ("These are the properties of the \"" + arguments[1]
2167 + "\" element (in \"" + element.origin.filename
2169 facets = element.facets()
2170 for facet in sorted(facets):
2171 if element.old_style:
2172 message += ("$(eol) $(grn)%s: $(red)%s$(nrm)" %
2173 (facet, escape_macros(element.get(facet))))
2175 message += ("$(eol) $(grn)%s: $(red)%s$(nrm)" %
2176 (facet, str(facets[facet])))
2178 message = "Element \"" + arguments[1] + "\" does not exist."
2179 elif arguments[0] == "result":
2180 if len(arguments) < 2:
2181 message = "You need to specify an expression."
2184 message = repr(eval(" ".join(arguments[1:])))
2185 except Exception as e:
2186 message = ("$(red)Your expression raised an exception...$(eol)"
2187 "$(eol)$(bld)%s$(nrm)" % e)
2188 elif arguments[0] == "log":
2189 if len(arguments) == 4:
2190 if re.match("^\d+$", arguments[3]) and int(arguments[3]) >= 0:
2191 stop = int(arguments[3])
2196 if len(arguments) >= 3:
2197 if re.match("^\d+$", arguments[2]) and int(arguments[2]) > 0:
2198 start = int(arguments[2])
2203 if len(arguments) >= 2:
2204 if (re.match("^\d+$", arguments[1])
2205 and 0 <= int(arguments[1]) <= 9):
2206 level = int(arguments[1])
2209 elif 0 <= actor.owner.account.get("loglevel", 0) <= 9:
2210 level = actor.owner.account.get("loglevel", 0)
2213 if level > -1 and start > -1 and stop > -1:
2214 message = get_loglines(level, start, stop)
2216 message = ("When specified, level must be 0-9 (default 1), "
2217 "start and stop must be >=1 (default 10 and 1).")
2219 message = "I don't know what \"" + parameters + "\" is."
2223 def command_create(actor, parameters):
2224 """Create an element if it does not exist."""
2226 message = "You must at least specify an element to create."
2227 elif not actor.owner:
2230 arguments = parameters.split()
2231 if len(arguments) == 1:
2232 arguments.append("")
2233 if len(arguments) == 2:
2234 element, filename = arguments
2235 if element in universe.contents:
2236 message = "The \"" + element + "\" element already exists."
2238 message = ("You create \"" +
2239 element + "\" within the universe.")
2240 logline = actor.owner.account.get(
2242 ) + " created an element: " + element
2244 logline += " in file " + filename
2245 if filename not in universe.files:
2247 " Warning: \"" + filename + "\" is not yet "
2248 "included in any other file and will not be read "
2249 "on startup unless this is remedied.")
2250 Element(element, universe, filename, old_style=True)
2252 elif len(arguments) > 2:
2253 message = "You can only specify an element and a filename."
2257 def command_destroy(actor, parameters):
2258 """Destroy an element if it exists."""
2261 message = "You must specify an element to destroy."
2263 if parameters not in universe.contents:
2264 message = "The \"" + parameters + "\" element does not exist."
2266 universe.contents[parameters].destroy()
2267 message = ("You destroy \"" + parameters
2268 + "\" within the universe.")
2270 actor.owner.account.get(
2272 ) + " destroyed an element: " + parameters,
2278 def command_set(actor, parameters):
2279 """Set a facet of an element."""
2281 message = "You must specify an element, a facet and a value."
2283 arguments = parameters.split(" ", 2)
2284 if len(arguments) == 1:
2285 message = ("What facet of element \"" + arguments[0]
2286 + "\" would you like to set?")
2287 elif len(arguments) == 2:
2288 message = ("What value would you like to set for the \"" +
2289 arguments[1] + "\" facet of the \"" + arguments[0]
2292 element, facet, value = arguments
2293 if element not in universe.contents:
2294 message = "The \"" + element + "\" element does not exist."
2296 universe.contents[element].set(facet, value)
2297 message = ("You have successfully (re)set the \"" + facet
2298 + "\" facet of element \"" + element
2299 + "\". Try \"show element " +
2300 element + "\" for verification.")
2304 def command_delete(actor, parameters):
2305 """Delete a facet from an element."""
2307 message = "You must specify an element and a facet."
2309 arguments = parameters.split(" ")
2310 if len(arguments) == 1:
2311 message = ("What facet of element \"" + arguments[0]
2312 + "\" would you like to delete?")
2313 elif len(arguments) != 2:
2314 message = "You may only specify an element and a facet."
2316 element, facet = arguments
2317 if element not in universe.contents:
2318 message = "The \"" + element + "\" element does not exist."
2319 elif facet not in universe.contents[element].facets():
2320 message = ("The \"" + element + "\" element has no \"" + facet
2323 universe.contents[element].remove_facet(facet)
2324 message = ("You have successfully deleted the \"" + facet
2325 + "\" facet of element \"" + element
2326 + "\". Try \"show element " +
2327 element + "\" for verification.")
2331 def command_error(actor, input_data):
2332 """Generic error for an unrecognized command word."""
2334 # 90% of the time use a generic error
2335 if random.randrange(10):
2336 message = "I'm not sure what \"" + input_data + "\" means..."
2338 # 10% of the time use the classic diku error
2340 message = "Arglebargle, glop-glyf!?!"
2342 # send the error message
2346 def daemonize(universe):
2347 """Fork and disassociate from everything."""
2349 # only if this is what we're configured to do
2350 if universe.contents["internal:process"].get("daemon"):
2352 # log before we start forking around, so the terminal gets the message
2353 log("Disassociating from the controlling terminal.")
2355 # fork off and die, so we free up the controlling terminal
2359 # switch to a new process group
2362 # fork some more, this time to free us from the old process group
2366 # reset the working directory so we don't needlessly tie up mounts
2369 # clear the file creation mask so we can bend it to our will later
2372 # redirect stdin/stdout/stderr and close off their former descriptors
2373 for stdpipe in range(3):
2375 sys.stdin = codecs.open("/dev/null", "r", "utf-8")
2376 sys.__stdin__ = codecs.open("/dev/null", "r", "utf-8")
2377 sys.stdout = codecs.open("/dev/null", "w", "utf-8")
2378 sys.stderr = codecs.open("/dev/null", "w", "utf-8")
2379 sys.__stdout__ = codecs.open("/dev/null", "w", "utf-8")
2380 sys.__stderr__ = codecs.open("/dev/null", "w", "utf-8")
2383 def create_pidfile(universe):
2384 """Write a file containing the current process ID."""
2385 pid = str(os.getpid())
2386 log("Process ID: " + pid)
2387 file_name = universe.contents["internal:process"].get("pidfile")
2389 if not os.path.isabs(file_name):
2390 file_name = os.path.join(universe.startdir, file_name)
2391 file_descriptor = codecs.open(file_name, "w", "utf-8")
2392 file_descriptor.write(pid + "\n")
2393 file_descriptor.flush()
2394 file_descriptor.close()
2397 def remove_pidfile(universe):
2398 """Remove the file containing the current process ID."""
2399 file_name = universe.contents["internal:process"].get("pidfile")
2401 if not os.path.isabs(file_name):
2402 file_name = os.path.join(universe.startdir, file_name)
2403 if os.access(file_name, os.W_OK):
2404 os.remove(file_name)
2407 def excepthook(excepttype, value, tracebackdata):
2408 """Handle uncaught exceptions."""
2410 # assemble the list of errors into a single string
2412 traceback.format_exception(excepttype, value, tracebackdata)
2415 # try to log it, if possible
2418 except Exception as e:
2419 # try to write it to stderr, if possible
2420 sys.stderr.write(message + "\nException while logging...\n%s" % e)
2423 def sighook(what, where):
2424 """Handle external signals."""
2427 message = "Caught signal: "
2429 # for a hangup signal
2430 if what == signal.SIGHUP:
2431 message += "hangup (reloading)"
2432 universe.reload_flag = True
2434 # for a terminate signal
2435 elif what == signal.SIGTERM:
2436 message += "terminate (halting)"
2437 universe.terminate_flag = True
2439 # catchall for unexpected signals
2441 message += str(what) + " (unhandled)"
2447 def override_excepthook():
2448 """Redefine sys.excepthook with our own."""
2449 sys.excepthook = excepthook
2452 def assign_sighook():
2453 """Assign a customized handler for some signals."""
2454 signal.signal(signal.SIGHUP, sighook)
2455 signal.signal(signal.SIGTERM, sighook)
2459 """This contains functions to be performed when starting the engine."""
2461 # see if a configuration file was specified
2462 if len(sys.argv) > 1:
2463 conffile = sys.argv[1]
2469 universe = Universe(conffile, True)
2471 # report any loglines which accumulated during setup
2472 for logline in universe.setup_loglines:
2474 universe.setup_loglines = []
2476 # log an initial message
2477 log("Started mudpy with command line: " + " ".join(sys.argv))
2479 # fork and disassociate
2482 # override the default exception handler so we get logging first thing
2483 override_excepthook()
2485 # set up custom signal handlers
2489 create_pidfile(universe)
2491 # pass the initialized universe back
2496 """These are functions performed when shutting down the engine."""
2498 # the loop has terminated, so save persistent data
2501 # log a final message
2502 log("Shutting down now.")
2504 # get rid of the pidfile
2505 remove_pidfile(universe)