Imported from archive.
[mudpy.git] / mudpy.py
1 """Core objects for the mudpy engine."""
2
3 # Copyright (c) 2005 mudpy, Jeremy Stanley <fungi@yuggoth.org>, all rights reserved.
4 # Licensed per terms in the LICENSE file distributed with this software.
5
6 # import some things we need
7 from ConfigParser import RawConfigParser
8 from md5 import new as new_md5
9 from os import R_OK, access, chmod, makedirs, stat
10 from os.path import abspath, dirname, exists, isabs, join as path_join
11 from random import choice, randrange
12 from re import match
13 from socket import AF_INET, SO_REUSEADDR, SOCK_STREAM, SOL_SOCKET, socket
14 from stat import S_IMODE, ST_MODE
15 from sys import stderr
16 from syslog import LOG_PID, LOG_INFO, LOG_DAEMON, closelog, openlog, syslog
17 from telnetlib import DO, DONT, ECHO, EOR, GA, IAC, LINEMODE, SB, SE, SGA, WILL, WONT
18 from time import asctime, sleep
19 from traceback import format_exception
20
21 def excepthook(excepttype, value, traceback):
22         """Handle uncaught exceptions."""
23
24         # assemble the list of errors into a single string
25         message = "".join(format_exception(excepttype, value, traceback))
26
27         # try to log it, if possible
28         try: log(message, 9)
29         except: pass
30
31         # try to write it to stderr, if possible
32         try: stderr.write(message)
33         except: pass
34
35 # redefine sys.excepthook with ours
36 import sys
37 sys.excepthook = excepthook
38
39 class Element:
40         """An element of the universe."""
41         def __init__(self, key, universe, filename=None):
42                 """Set up a new element."""
43
44                 # not owned by a user by default (used for avatars)
45                 self.owner = None
46
47                 # no contents in here by default
48                 self.contents = {}
49
50                 # an event queue for the element
51                 self.events = {}
52
53                 # keep track of our key name
54                 self.key = key
55
56                 # parse out appropriate category and subkey names, add to list
57                 if self.key.find(":") > 0:
58                         self.category, self.subkey = self.key.split(":", 1)
59                 else:
60                         self.category = "other"
61                         self.subkey = self.key
62                 if not self.category in universe.categories: self.category = "other"
63                 universe.categories[self.category][self.subkey] = self
64
65                 # get an appropriate filename for the origin
66                 if not filename: filename = universe.default_origins[self.category]
67                 if not isabs(filename): filename = abspath(filename)
68
69                 # add the file if it doesn't exist yet
70                 if not filename in universe.files: DataFile(filename, universe)
71
72                 # record a pointer to the origin file
73                 self.origin = universe.files[filename]
74
75                 # add a data section to the origin if necessary
76                 if not self.origin.data.has_section(self.key):
77                         self.origin.data.add_section(self.key)
78
79                 # add this element to the universe contents
80                 universe.contents[self.key] = self
81
82         def destroy(self):
83                 """Remove an element from the universe and destroy it."""
84                 self.origin.data.remove_section(self.key)
85                 del universe.categories[self.category][self.subkey]
86                 del universe.contents[self.key]
87                 del self
88         def facets(self):
89                 """Return a list of non-inherited facets for this element."""
90                 if self.key in self.origin.data.sections():
91                         return self.origin.data.options(self.key)
92                 else: return []
93         def has_facet(self, facet):
94                 """Return whether the non-inherited facet exists."""
95                 return facet in self.facets()
96         def remove_facet(self, facet):
97                 """Remove a facet from the element."""
98                 if self.has_facet(facet):
99                         self.origin.data.remove_option(self.key, facet)
100                         self.origin.modified = True
101         def ancestry(self):
102                 """Return a list of the element's inheritance lineage."""
103                 if self.has_facet("inherit"):
104                         ancestry = self.getlist("inherit")
105                         for parent in ancestry[:]:
106                                 ancestors = universe.contents[parent].ancestry()
107                                 for ancestor in ancestors:
108                                         if ancestor not in ancestry: ancestry.append(ancestor)
109                         return ancestry
110                 else: return []
111         def get(self, facet, default=None):
112                 """Retrieve values."""
113                 if default is None: default = ""
114                 if self.origin.data.has_option(self.key, facet):
115                         return self.origin.data.get(self.key, facet)
116                 elif self.has_facet("inherit"):
117                         for ancestor in self.ancestry():
118                                 if universe.contents[ancestor].has_facet(facet):
119                                         return universe.contents[ancestor].get(facet)
120                 else: return default
121         def getboolean(self, facet, default=None):
122                 """Retrieve values as boolean type."""
123                 if default is None: default=False
124                 if self.origin.data.has_option(self.key, facet):
125                         return self.origin.data.getboolean(self.key, facet)
126                 elif self.has_facet("inherit"):
127                         for ancestor in self.ancestry():
128                                 if universe.contents[ancestor].has_facet(facet):
129                                         return universe.contents[ancestor].getboolean(facet)
130                 else: return default
131         def getint(self, facet, default=None):
132                 """Return values as int/long type."""
133                 if default is None: default = 0
134                 if self.origin.data.has_option(self.key, facet):
135                         return self.origin.data.getint(self.key, facet)
136                 elif self.has_facet("inherit"):
137                         for ancestor in self.ancestry():
138                                 if universe.contents[ancestor].has_facet(facet):
139                                         return universe.contents[ancestor].getint(facet)
140                 else: return default
141         def getfloat(self, facet, default=None):
142                 """Return values as float type."""
143                 if default is None: default = 0.0
144                 if self.origin.data.has_option(self.key, facet):
145                         return self.origin.data.getfloat(self.key, facet)
146                 elif self.has_facet("inherit"):
147                         for ancestor in self.ancestry():
148                                 if universe.contents[ancestor].has_facet(facet):
149                                         return universe.contents[ancestor].getfloat(facet)
150                 else: return default
151         def getlist(self, facet, default=None):
152                 """Return values as list type."""
153                 if default is None: default = []
154                 value = self.get(facet)
155                 if value: return makelist(value)
156                 else: return default
157         def getdict(self, facet, default=None):
158                 """Return values as dict type."""
159                 if default is None: default = {}
160                 value = self.get(facet)
161                 if value: return makedict(value)
162                 else: return default
163         def set(self, facet, value):
164                 """Set values."""
165                 if not self.has_facet(facet) or not self.get(facet) == value:
166                         if type(value) is long: value = str(value)
167                         elif not type(value) is str: value = repr(value)
168                         self.origin.data.set(self.key, facet, value)
169                         self.origin.modified = True
170         def append(self, facet, value):
171                 """Append value tp a list."""
172                 if type(value) is long: value = str(value)
173                 elif not type(value) is str: value = repr(value)
174                 newlist = self.getlist(facet)
175                 newlist.append(value)
176                 self.set(facet, newlist)
177
178         def new_event(self, action, when=None):
179                 """Create, attach and enqueue an event element."""
180
181                 # if when isn't specified, that means now
182                 if not when: when = universe.get_time()
183
184                 # events are elements themselves
185                 event = Element("event:" + self.key + ":" + counter)
186
187         def send(self, message, eol="$(eol)"):
188                 """Convenience method to pass messages to an owner."""
189                 if self.owner: self.owner.send(message, eol)
190
191         def can_run(self, command):
192                 """Check if the user can run this command object."""
193
194                 # has to be in the commands category
195                 if command not in universe.categories["command"].values(): result = False
196
197                 # avatars of administrators can run any command
198                 elif self.owner and self.owner.account.getboolean("administrator"): result = True
199
200                 # everyone can run non-administrative commands
201                 elif not command.getboolean("administrative"): result = True
202
203                 # otherwise the command cannot be run by this actor
204                 else: result = False
205
206                 # pass back the result
207                 return result
208
209         def go_to(self, location):
210                 """Relocate the element to a specific location."""
211                 current = self.get("location")
212                 if current and self.key in universe.contents[current].contents:
213                         del universe.contents[current].contents[self.key]
214                 if location in universe.contents: self.set("location", location)
215                 universe.contents[location].contents[self.key] = self
216                 self.look_at(location)
217         def go_home(self):
218                 """Relocate the element to its default location."""
219                 self.go_to(self.get("default_location"))
220                 self.echo_to_location("You suddenly realize that " + self.get("name") + " is here.")
221         def move_direction(self, direction):
222                 """Relocate the element in a specified direction."""
223                 self.echo_to_location(self.get("name") + " exits " + universe.categories["internal"]["directions"].getdict(direction)["exit"] + ".")
224                 self.send("You exit " + universe.categories["internal"]["directions"].getdict(direction)["exit"] + ".")
225                 self.go_to(universe.contents[self.get("location")].link_neighbor(direction))
226                 self.echo_to_location(self.get("name") + " arrives from " + universe.categories["internal"]["directions"].getdict(direction)["enter"] + ".")
227         def look_at(self, key):
228                 """Show an element to another element."""
229                 if self.owner:
230                         element = universe.contents[key]
231                         message = ""
232                         name = element.get("name")
233                         if name: message += "$(cyn)" + name + "$(nrm)$(eol)"
234                         description = element.get("description")
235                         if description: message += description + "$(eol)"
236                         portal_list = element.portals().keys()
237                         if portal_list:
238                                 portal_list.sort()
239                                 message += "$(cyn)[ Exits: " + ", ".join(portal_list) + " ]$(nrm)$(eol)"
240                         for element in universe.contents[self.get("location")].contents.values():
241                                 if element.getboolean("is_actor") and element is not self:
242                                         message += "$(yel)" + element.get("name") + " is here.$(nrm)$(eol)"
243                         self.send(message)
244         def portals(self):
245                 """Map the portal directions for a room to neighbors."""
246                 portals = {}
247                 if match("""^location:-?\d+,-?\d+,-?\d+$""", self.key):
248                         coordinates = [(int(x)) for x in self.key.split(":")[1].split(",")]
249                         directions = universe.categories["internal"]["directions"]
250                         offsets = dict([(x, directions.getdict(x)["vector"]) for x in directions.facets()])
251                         for portal in self.getlist("gridlinks"):
252                                 adjacent = map(lambda c,o: c+o, coordinates, offsets[portal])
253                                 neighbor = "location:" + ",".join([(str(x)) for x in adjacent])
254                                 if neighbor in universe.contents: portals[portal] = neighbor
255                 for facet in self.facets():
256                         if facet.startswith("link_"):
257                                 neighbor = self.get(facet)
258                                 if neighbor in universe.contents:
259                                         portal = facet.split("_")[1]
260                                         portals[portal] = neighbor
261                 return portals
262         def link_neighbor(self, direction):
263                 """Return the element linked in a given direction."""
264                 portals = self.portals()
265                 if direction in portals: return portals[direction]
266         def echo_to_location(self, message):
267                 """Show a message to other elements in the current location."""
268                 for element in universe.contents[self.get("location")].contents.values():
269                         if element is not self: element.send(message)
270
271 class DataFile:
272         """A file containing universe elements."""
273         def __init__(self, filename, universe):
274                 self.modified = False
275                 self.data = RawConfigParser()
276                 if access(filename, R_OK): self.data.read(filename)
277                 self.filename = filename
278                 universe.files[filename] = self
279                 if self.data.has_option("__control__", "include_files"):
280                         includes = makelist(self.data.get("__control__", "include_files"))
281                 else: includes = []
282                 if self.data.has_option("__control__", "default_files"):
283                         origins = makedict(self.data.get("__control__", "default_files"))
284                         for key in origins.keys():
285                                 if not key in includes: includes.append(key)
286                                 universe.default_origins[key] = origins[key]
287                                 if not key in universe.categories:
288                                         universe.categories[key] = {}
289                 if self.data.has_option("__control__", "private_files"):
290                         for item in makelist(self.data.get("__control__", "private_files")):
291                                 if not item in includes: includes.append(item)
292                                 if not item in universe.private_files:
293                                         if not isabs(item):
294                                                 item = path_join(dirname(filename), item)
295                                         universe.private_files.append(item)
296                 for section in self.data.sections():
297                         if section != "__control__":
298                                 Element(section, universe, filename)
299                 for include_file in includes:
300                         if not isabs(include_file):
301                                 include_file = path_join(dirname(filename), include_file)
302                         DataFile(include_file, universe)
303         def is_writeable(self):
304                 """Returns True if the __control__ read_only is False."""
305                 return not self.data.has_option("__control__", "read_only") or not self.data.getboolean("__control__", "read_only")
306         def save(self):
307                 """Write the data, if necessary."""
308
309                 # when modified, writeable and has content or the file exists
310                 if self.modified and self.is_writeable() and ( self.data.sections() or exists(self.filename) ):
311
312                         # make parent directories if necessary
313                         if not exists(dirname(self.filename)):
314                                 makedirs(dirname(self.filename))
315
316                         # our data file
317                         file_descriptor = file(self.filename, "w")
318
319                         # if it's marked private, chmod it appropriately
320                         if self.filename in universe.private_files and oct(S_IMODE(stat(self.filename)[ST_MODE])) != 0600:
321                                 chmod(self.filename, 0600)
322
323                         # write it back sorted, instead of using ConfigParser
324                         sections = self.data.sections()
325                         sections.sort()
326                         for section in sections:
327                                 file_descriptor.write("[" + section + "]\n")
328                                 options = self.data.options(section)
329                                 options.sort()
330                                 for option in options:
331                                         file_descriptor.write(option + " = " + self.data.get(section, option) + "\n")
332                                 file_descriptor.write("\n")
333
334                         # flush and close the file
335                         file_descriptor.flush()
336                         file_descriptor.close()
337
338                         # unset the modified flag
339                         self.modified = False
340
341 class Universe:
342         """The universe."""
343         def __init__(self, filename=""):
344                 """Initialize the universe."""
345                 self.categories = {}
346                 self.contents = {}
347                 self.default_origins = {}
348                 self.files = {}
349                 self.private_files = []
350                 self.loglines = {}
351                 self.pending_events_long = {}
352                 self.pending_events_short = {}
353                 self.userlist = []
354                 self.terminate_world = False
355                 self.reload_modules = False
356                 if not filename:
357                         possible_filenames = [
358                                 ".mudpyrc",
359                                 ".mudpy/mudpyrc",
360                                 ".mudpy/mudpy.conf",
361                                 "mudpy.conf",
362                                 "etc/mudpy.conf",
363                                 "/usr/local/mudpy/mudpy.conf",
364                                 "/usr/local/mudpy/etc/mudpy.conf",
365                                 "/etc/mudpy/mudpy.conf",
366                                 "/etc/mudpy.conf"
367                                 ]
368                         for filename in possible_filenames:
369                                 if access(filename, R_OK): break
370                 if not isabs(filename):
371                         filename = abspath(filename)
372                 DataFile(filename, self)
373         def save(self):
374                 """Save the universe to persistent storage."""
375                 for key in self.files: self.files[key].save()
376
377         def initialize_server_socket(self):
378                 """Create and open the listening socket."""
379
380                 # create a new ipv4 stream-type socket object
381                 self.listening_socket = socket(AF_INET, SOCK_STREAM)
382
383                 # set the socket options to allow existing open ones to be
384                 # reused (fixes a bug where the server can't bind for a minute
385                 # when restarting on linux systems)
386                 self.listening_socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
387
388                 # bind the socket to to our desired server ipa and port
389                 self.listening_socket.bind((self.categories["internal"]["network"].get("host"), self.categories["internal"]["network"].getint("port")))
390
391                 # disable blocking so we can proceed whether or not we can
392                 # send/receive
393                 self.listening_socket.setblocking(0)
394
395                 # start listening on the socket
396                 self.listening_socket.listen(1)
397
398                 # note that we're now ready for user connections
399                 log("Waiting for connection(s)...")
400
401         def get_time(self):
402                 """Convenience method to get the elapsed time counter."""
403                 return self.categories["internal"]["counters"].getint("elapsed")
404
405 class User:
406         """This is a connected user."""
407
408         def __init__(self):
409                 """Default values for the in-memory user variables."""
410                 self.address = ""
411                 self.last_address = ""
412                 self.connection = None
413                 self.authenticated = False
414                 self.password_tries = 0
415                 self.state = "initial"
416                 self.menu_seen = False
417                 self.error = ""
418                 self.input_queue = []
419                 self.output_queue = []
420                 self.partial_input = ""
421                 self.echoing = True
422                 self.received_newline = True
423                 self.terminator = IAC+GA
424                 self.negotiation_pause = 0
425                 self.avatar = None
426                 self.account = None
427
428         def quit(self):
429                 """Log, close the connection and remove."""
430                 if self.account: name = self.account.get("name")
431                 else: name = ""
432                 if name: message = "User " + name
433                 else: message = "An unnamed user"
434                 message += " logged out."
435                 log(message, 2)
436                 self.deactivate_avatar()
437                 self.connection.close()
438                 self.remove()
439
440         def reload(self):
441                 """Save, load a new user and relocate the connection."""
442
443                 # get out of the list
444                 self.remove()
445
446                 # create a new user object
447                 new_user = User()
448
449                 # set everything else equivalent
450                 for attribute in [
451                         "address",
452                         "last_address",
453                         "connection",
454                         "authenticated",
455                         "password_tries",
456                         "state",
457                         "menu_seen",
458                         "error",
459                         "input_queue",
460                         "output_queue",
461                         "partial_input",
462                         "echoing",
463                         "received_newline",
464                         "terminator",
465                         "negotiation_pause",
466                         "avatar",
467                         "account"
468                         ]:
469                         exec("new_user." + attribute + " = self." + attribute)
470
471                 # add it to the list
472                 universe.userlist.append(new_user)
473
474                 # get rid of the old user object
475                 del(self)
476
477         def replace_old_connections(self):
478                 """Disconnect active users with the same name."""
479
480                 # the default return value
481                 return_value = False
482
483                 # iterate over each user in the list
484                 for old_user in universe.userlist:
485
486                         # the name is the same but it's not us
487                         if old_user.account.get("name") == self.account.get("name") and old_user is not self:
488
489                                 # make a note of it
490                                 log("User " + self.account.get("name") + " reconnected--closing old connection to " + old_user.address + ".", 2)
491                                 old_user.send("$(eol)$(red)New connection from " + self.address + ". Terminating old connection...$(nrm)$(eol)", flush=True, add_prompt=False)
492
493                                 # close the old connection
494                                 old_user.connection.close()
495
496                                 # replace the old connection with this one
497                                 old_user.send("$(eol)$(red)Taking over old connection from " + old_user.address + ".$(nrm)")
498                                 old_user.connection = self.connection
499                                 old_user.last_address = old_user.address
500                                 old_user.address = self.address
501                                 old_user.echoing = self.echoing
502
503                                 # take this one out of the list and delete
504                                 self.remove()
505                                 del(self)
506                                 return_value = True
507                                 break
508
509                 # true if an old connection was replaced, false if not
510                 return return_value
511
512         def authenticate(self):
513                 """Flag the user as authenticated and disconnect duplicates."""
514                 if not self.state is "authenticated":
515                         log("User " + self.account.get("name") + " logged in.", 2)
516                         self.authenticated = True
517                         if self.account.subkey in universe.categories["internal"]["limits"].getlist("default_admins"):
518                                 self.account.set("administrator", "True")
519
520         def show_menu(self):
521                 """Send the user their current menu."""
522                 if not self.menu_seen:
523                         self.menu_choices = get_menu_choices(self)
524                         self.send(get_menu(self.state, self.error, self.echoing, self.terminator, self.menu_choices), "")
525                         self.menu_seen = True
526                         self.error = False
527                         self.adjust_echoing()
528
529         def adjust_echoing(self):
530                 """Adjust echoing to match state menu requirements."""
531                 if self.echoing and not menu_echo_on(self.state): self.echoing = False
532                 elif not self.echoing and menu_echo_on(self.state): self.echoing = True
533
534         def remove(self):
535                 """Remove a user from the list of connected users."""
536                 universe.userlist.remove(self)
537
538         def send(self, output, eol="$(eol)", raw=False, flush=False, add_prompt=True, just_prompt=False):
539                 """Send arbitrary text to a connected user."""
540
541                 # unless raw mode is on, clean it up all nice and pretty
542                 if not raw:
543
544                         # strip extra $(eol) off if present
545                         while output.startswith("$(eol)"): output = output[6:]
546                         while output.endswith("$(eol)"): output = output[:-6]
547
548                         # we'll take out GA or EOR and add them back on the end
549                         if output.endswith(IAC+GA) or output.endswith(IAC+EOR):
550                                 terminate = True
551                                 output = output[:-2]
552                         else: terminate = False
553
554                         # start with a newline, append the message, then end
555                         # with the optional eol string passed to this function
556                         # and the ansi escape to return to normal text
557                         if not just_prompt: output = "$(eol)$(eol)" + output
558                         output += eol + chr(27) + "[0m"
559
560                         # tack on a prompt if active
561                         if self.state == "active":
562                                 if not just_prompt: output += "$(eol)"
563                                 if add_prompt: output += "> "
564
565                         # find and replace macros in the output
566                         output = replace_macros(self, output)
567
568                         # wrap the text at 80 characters
569                         output = wrap_ansi_text(output, 80)
570
571                         # tack the terminator back on
572                         if terminate: output += self.terminator
573
574                 # drop the output into the user's output queue
575                 self.output_queue.append(output)
576
577                 # if this is urgent, flush all pending output
578                 if flush: self.flush()
579
580         def pulse(self):
581                 """All the things to do to the user per increment."""
582
583                 # if the world is terminating, disconnect
584                 if universe.terminate_world:
585                         self.state = "disconnecting"
586                         self.menu_seen = False
587
588                 # if output is paused, decrement the counter
589                 if self.state == "initial":
590                         if self.negotiation_pause: self.negotiation_pause -= 1
591                         else: self.state = "entering_account_name"
592
593                 # show the user a menu as needed
594                 elif not self.state == "active": self.show_menu()
595
596                 # flush any pending output in teh queue
597                 self.flush()
598
599                 # disconnect users with the appropriate state
600                 if self.state == "disconnecting": self.quit()
601
602                 # check for input and add it to the queue
603                 self.enqueue_input()
604
605                 # there is input waiting in the queue
606                 if self.input_queue: handle_user_input(self)
607
608         def flush(self):
609                 """Try to send the last item in the queue and remove it."""
610                 if self.output_queue:
611                         if self.received_newline:
612                                 self.received_newline = False
613                                 if self.output_queue[0].startswith("\r\n"):
614                                         self.output_queue[0] = self.output_queue[0][2:]
615                         try:
616                                 self.connection.send(self.output_queue[0])
617                                 del self.output_queue[0]
618                         except:
619                                 pass
620
621
622         def enqueue_input(self):
623                 """Process and enqueue any new input."""
624
625                 # check for some input
626                 try:
627                         input_data = self.connection.recv(1024)
628                 except:
629                         input_data = ""
630
631                 # we got something
632                 if input_data:
633
634                         # tack this on to any previous partial
635                         self.partial_input += input_data
636
637                         # reply to and remove any IAC negotiation codes
638                         self.negotiate_telnet_options()
639
640                         # separate multiple input lines
641                         new_input_lines = self.partial_input.split("\n")
642
643                         # if input doesn't end in a newline, replace the
644                         # held partial input with the last line of it
645                         if not self.partial_input.endswith("\n"):
646                                 self.partial_input = new_input_lines.pop()
647
648                         # otherwise, chop off the extra null input and reset
649                         # the held partial input
650                         else:
651                                 new_input_lines.pop()
652                                 self.partial_input = ""
653
654                         # iterate over the remaining lines
655                         for line in new_input_lines:
656
657                                 # remove a trailing carriage return
658                                 if line.endswith("\r"): line = line.rstrip("\r")
659
660                                 # log non-printable characters remaining
661                                 removed = filter(lambda x: (x < " " or x > "~"), line)
662                                 if removed:
663                                         logline = "Non-printable characters from "
664                                         if self.account and self.account.get("name"): logline += self.account.get("name") + ": "
665                                         else: logline += "unknown user: "
666                                         logline += repr(removed)
667                                         log(logline, 4)
668
669                                 # filter out non-printables
670                                 line = filter(lambda x: " " <= x <= "~", line)
671
672                                 # strip off extra whitespace
673                                 line = line.strip()
674
675                                 # put on the end of the queue
676                                 self.input_queue.append(line)
677
678         def negotiate_telnet_options(self):
679                 """Reply to/remove partial_input telnet negotiation options."""
680
681                 # start at the begining of the input
682                 position = 0
683
684                 # make a local copy to play with
685                 text = self.partial_input
686
687                 # as long as we haven't checked it all
688                 while position < len(text):
689
690                         # jump to the first IAC you find
691                         position = text.find(IAC, position)
692
693                         # if there wasn't an IAC in the input, skip to the end
694                         if position < 0: position = len(text)
695
696                         # replace a double (literal) IAC if there's an LF later
697                         elif len(text) > position+1 and text[position+1] == IAC:
698                                 if text.find("\n", position) > 0: text = text.replace(IAC+IAC, IAC)
699                                 else: position += 1
700                                 position += 1
701
702                         # this must be an option negotiation
703                         elif len(text) > position+2 and text[position+1] in (DO, DONT, WILL, WONT):
704
705                                 negotiation = text[position+1:position+3]
706
707                                 # if we turned echo off, ignore the confirmation
708                                 if not self.echoing and negotiation == DO+ECHO: pass
709
710                                 # allow LINEMODE
711                                 elif negotiation == WILL+LINEMODE: self.send(IAC+DO+LINEMODE, raw=True)
712
713                                 # if the client likes EOR instead of GA, make a note of it
714                                 elif negotiation == DO+EOR: self.terminator = IAC+EOR
715                                 elif negotiation == DONT+EOR and self.terminator == IAC+EOR:
716                                         self.terminator = IAC+GA
717
718                                 # if the client doesn't want GA, oblige
719                                 elif negotiation == DO+SGA and self.terminator == IAC+GA:
720                                         self.terminator = ""
721                                         self.send(IAC+WILL+SGA, raw=True)
722
723                                 # we don't want to allow anything else
724                                 elif text[position+1] == DO: self.send(IAC+WONT+text[position+2], raw=True)
725                                 elif text[position+1] == WILL: self.send(IAC+DONT+text[position+2], raw=True)
726
727                                 # strip the negotiation from the input
728                                 text = text.replace(text[position:position+3], "")
729
730                         # get rid of IAC SB .* IAC SE
731                         elif len(text) > position+4 and text[position:position+2] == IAC+SB:
732                                 end_subnegotiation = text.find(IAC+SE, position)
733                                 if end_subnegotiation > 0: text = text[:position] + text[end_subnegotiation+2:]
734                                 else: position += 1
735
736                         # otherwise, strip out a two-byte IAC command
737                         elif len(text) > position+2: text = text.replace(text[position:position+2], "")
738
739                         # and this means we got the begining of an IAC
740                         else: position += 1
741
742                 # replace the input with our cleaned-up text
743                 self.partial_input = text
744
745         def new_avatar(self):
746                 """Instantiate a new, unconfigured avatar for this user."""
747                 counter = 0
748                 while "avatar:" + self.account.get("name") + ":" + str(counter) in universe.categories["actor"].keys(): counter += 1
749                 self.avatar = Element("actor:avatar:" + self.account.get("name") + ":" + str(counter), universe)
750                 self.avatar.append("inherit", "archetype:avatar")
751                 self.account.append("avatars", self.avatar.key)
752
753         def delete_avatar(self, avatar):
754                 """Remove an avatar from the world and from the user's list."""
755                 if self.avatar is universe.contents[avatar]: self.avatar = None
756                 universe.contents[avatar].destroy()
757                 avatars = self.account.getlist("avatars")
758                 avatars.remove(avatar)
759                 self.account.set("avatars", avatars)
760
761         def activate_avatar_by_index(self, index):
762                 """Enter the world with a particular indexed avatar."""
763                 self.avatar = universe.contents[self.account.getlist("avatars")[index]]
764                 self.avatar.owner = self
765                 self.state = "active"
766                 self.avatar.go_home()
767
768         def deactivate_avatar(self):
769                 """Have the active avatar leave the world."""
770                 if self.avatar:
771                         current = self.avatar.get("location")
772                         self.avatar.set("default_location", current)
773                         self.avatar.echo_to_location("You suddenly wonder where " + self.avatar.get("name") + " went.")
774                         del universe.contents[current].contents[self.avatar.key]
775                         self.avatar.remove_facet("location")
776                         self.avatar.owner = None
777                         self.avatar = None
778
779         def destroy(self):
780                 """Destroy the user and associated avatars."""
781                 for avatar in self.account.getlist("avatars"): self.delete_avatar(avatar)
782                 self.account.destroy()
783
784         def list_avatar_names(self):
785                 """List names of assigned avatars."""
786                 return [ universe.contents[avatar].get("name") for avatar in self.account.getlist("avatars") ]
787
788 def makelist(value):
789         """Turn string into list type."""
790         if value[0] + value[-1] == "[]": return eval(value)
791         else: return [ value ]
792
793 def makedict(value):
794         """Turn string into dict type."""
795         if value[0] + value[-1] == "{}": return eval(value)
796         elif value.find(":") > 0: return eval("{" + value + "}")
797         else: return { value: None }
798
799 def broadcast(message, add_prompt=True):
800         """Send a message to all connected users."""
801         for each_user in universe.userlist: each_user.send("$(eol)" + message, add_prompt=add_prompt)
802
803 def log(message, level=0):
804         """Log a message."""
805
806         # a couple references we need
807         file_name = universe.categories["internal"]["logging"].get("file")
808         max_log_lines = universe.categories["internal"]["logging"].getint("max_log_lines")
809         syslog_name = universe.categories["internal"]["logging"].get("syslog")
810         timestamp = asctime()[4:19]
811
812         # turn the message into a list of lines
813         lines = filter(lambda x: x!="", [(x.rstrip()) for x in message.split("\n")])
814
815         # send the timestamp and line to a file
816         if file_name:
817                 file_descriptor = file(file_name, "a")
818                 for line in lines: file_descriptor.write(timestamp + " " + line + "\n")
819                 file_descriptor.flush()
820                 file_descriptor.close()
821
822         # send the timestamp and line to standard output
823         if universe.categories["internal"]["logging"].getboolean("stdout"):
824                 for line in lines: print(timestamp + " " + line)
825
826         # send the line to the system log
827         if syslog_name:
828                 openlog(syslog_name, LOG_PID, LOG_INFO | LOG_DAEMON)
829                 for line in lines: syslog(line)
830                 closelog()
831
832         # display to connected administrators
833         for user in universe.userlist:
834                 if user.state == "active" and user.account.getboolean("administrator") and user.account.getint("loglevel") <= level:
835                         # iterate over every line in the message
836                         full_message = ""
837                         for line in lines:
838                                 full_message += "$(bld)$(red)" + timestamp + " " + line + "$(nrm)$(eol)"
839                         user.send(full_message, flush=True)
840
841         # add to the recent log list
842         for line in lines:
843                 while 0 < len(universe.loglines) >= max_log_lines: del universe.loglines[0]
844                 universe.loglines.append((level, timestamp + " " + line))
845
846 def get_loglines(level, start, stop=0):
847         """Return a specific range of loglines filtered by level."""
848
849         # begin with a blank message
850         message = ""
851
852         # filter the log lines
853         loglines = filter(lambda x,y: x>=level, universe.loglines)
854
855         # we need this in several places
856         count = len(loglines)
857
858         # don't proceed if there are no lines
859         if count:
860
861                 # can't start before the begining or at the end
862                 if start > count: start = count
863                 if start < 1: start = 1
864
865                 # can't stop before we start
866                 if stop >= start: stop = start - 1
867
868                 # some preamble
869                 message += "There are " + str(len(universe.loglist))
870                 message += " log lines in memory and " + str(count)
871                 message += " at or above level " + str(level) + "."
872                 message += " The lines from " + str(stop)
873                 message += " to " + str(start) + " are:$(eol)$(eol)"
874
875                 # add the text from the selected lines
876                 for line in loglines[-start:-stop]:
877                         message += "   " + line[1] + "$(eol)"
878
879         # pass it back
880         return message
881
882 def wrap_ansi_text(text, width):
883         """Wrap text with arbitrary width while ignoring ANSI colors."""
884
885         # the current position in the entire text string, including all
886         # characters, printable or otherwise
887         absolute_position = 0
888
889         # the current text position relative to the begining of the line,
890         # ignoring color escape sequences
891         relative_position = 0
892
893         # whether the current character is part of a color escape sequence
894         escape = False
895
896         # iterate over each character from the begining of the text
897         for each_character in text:
898
899                 # the current character is the escape character
900                 if each_character == chr(27):
901                         escape = True
902
903                 # the current character is within an escape sequence
904                 elif escape:
905
906                         # the current character is m, which terminates the
907                         # current escape sequence
908                         if each_character == "m":
909                                 escape = False
910
911                 # the current character is a newline, so reset the relative
912                 # position (start a new line)
913                 elif each_character == "\n":
914                         relative_position = 0
915
916                 # the current character meets the requested maximum line width,
917                 # so we need to backtrack and find a space at which to wrap
918                 elif relative_position == width:
919
920                         # distance of the current character examined from the
921                         # relative position
922                         wrap_offset = 0
923
924                         # count backwards until we find a space
925                         while text[absolute_position - wrap_offset] != " ":
926                                 wrap_offset += 1
927
928                         # insert an eol in place of the space
929                         text = text[:absolute_position - wrap_offset] + "\r\n" + text[absolute_position - wrap_offset + 1:]
930
931                         # increase the absolute position because an eol is two
932                         # characters but the space it replaced was only one
933                         absolute_position += 1
934
935                         # now we're at the begining of a new line, plus the
936                         # number of characters wrapped from the previous line
937                         relative_position = wrap_offset
938
939                 # as long as the character is not a carriage return and the
940                 # other above conditions haven't been met, count it as a
941                 # printable character
942                 elif each_character != "\r":
943                         relative_position += 1
944
945                 # increase the absolute position for every character
946                 absolute_position += 1
947
948         # return the newly-wrapped text
949         return text
950
951 def weighted_choice(data):
952         """Takes a dict weighted by value and returns a random key."""
953
954         # this will hold our expanded list of keys from the data
955         expanded = []
956
957         # create thee expanded list of keys
958         for key in data.keys():
959                 for count in range(data[key]):
960                         expanded.append(key)
961
962         # return one at random
963         return choice(expanded)
964
965 def random_name():
966         """Returns a random character name."""
967
968         # the vowels and consonants needed to create romaji syllables
969         vowels = [ "a", "i", "u", "e", "o" ]
970         consonants = ["'", "k", "z", "s", "sh", "z", "j", "t", "ch", "ts", "d", "n", "h", "f", "m", "y", "r", "w" ]
971
972         # this dict will hold our weighted list of syllables
973         syllables = {}
974
975         # generate the list with an even weighting
976         for consonant in consonants:
977                 for vowel in vowels:
978                         syllables[consonant + vowel] = 1
979
980         # we'll build the name into this string
981         name = ""
982
983         # create a name of random length from the syllables
984         for syllable in range(randrange(2, 6)):
985                 name += weighted_choice(syllables)
986
987         # strip any leading quotemark, capitalize and return the name
988         return name.strip("'").capitalize()
989
990 def replace_macros(user, text, is_input=False):
991         """Replaces macros in text output."""
992
993         # loop until broken
994         while True:
995
996                 # third person pronouns
997                 pronouns = {
998                         "female": { "obj": "her", "pos": "hers", "sub": "she" },
999                         "male": { "obj": "him", "pos": "his", "sub": "he" },
1000                         "neuter": { "obj": "it", "pos": "its", "sub": "it" }
1001                         }
1002
1003                 # a dict of replacement macros
1004                 macros = {
1005                         "$(eol)": "\r\n",
1006                         "$(bld)": chr(27) + "[1m",
1007                         "$(nrm)": chr(27) + "[0m",
1008                         "$(blk)": chr(27) + "[30m",
1009                         "$(blu)": chr(27) + "[34m",
1010                         "$(cyn)": chr(27) + "[36m",
1011                         "$(grn)": chr(27) + "[32m",
1012                         "$(mgt)": chr(27) + "[35m",
1013                         "$(red)": chr(27) + "[31m",
1014                         "$(yel)": chr(27) + "[33m",
1015                         }
1016
1017                 # add dynamic macros where possible
1018                 if user.account:
1019                         account_name = user.account.get("name")
1020                         if account_name:
1021                                 macros["$(account)"] = account_name
1022                 if user.avatar:
1023                         avatar_gender = user.avatar.get("gender")
1024                         if avatar_gender:
1025                                 macros["$(tpop)"] = pronouns[avatar_gender]["obj"]
1026                                 macros["$(tppp)"] = pronouns[avatar_gender]["pos"]
1027                                 macros["$(tpsp)"] = pronouns[avatar_gender]["sub"]
1028
1029                 # find and replace per the macros dict
1030                 macro_start = text.find("$(")
1031                 if macro_start == -1: break
1032                 macro_end = text.find(")", macro_start) + 1
1033                 macro = text[macro_start:macro_end]
1034                 if macro in macros.keys():
1035                         text = text.replace(macro, macros[macro])
1036
1037                 # if we get here, log and replace it with null
1038                 else:
1039                         text = text.replace(macro, "")
1040                         if not is_input:
1041                                 log("Unexpected replacement macro " + macro + " encountered.", 6)
1042
1043         # replace the look-like-a-macro sequence
1044         text = text.replace("$_(", "$(")
1045
1046         return text
1047
1048 def escape_macros(text):
1049         """Escapes replacement macros in text."""
1050         return text.replace("$(", "$_(")
1051
1052 def check_time(frequency):
1053         """Check for a factor of the current increment count."""
1054         if type(frequency) is str:
1055                 frequency = universe.categories["internal"]["time"].getint(frequency)
1056         if not "counters" in universe.categories["internal"]:
1057                 Element("internal:counters", universe)
1058         return not universe.categories["internal"]["counters"].getint("elapsed") % frequency
1059
1060 def on_pulse():
1061         """The things which should happen on each pulse, aside from reloads."""
1062
1063         # open the listening socket if it hasn't been already
1064         if not hasattr(universe, "listening_socket"):
1065                 universe.initialize_server_socket()
1066
1067         # assign a user if a new connection is waiting
1068         user = check_for_connection(universe.listening_socket)
1069         if user: universe.userlist.append(user)
1070
1071         # iterate over the connected users
1072         for user in universe.userlist: user.pulse()
1073
1074         # update the log every now and then
1075         if check_time("frequency_log"):
1076                 log(str(len(universe.userlist)) + " connection(s)")
1077
1078         # periodically save everything
1079         if check_time("frequency_save"):
1080                 universe.save()
1081
1082         # pause for a configurable amount of time (decimal seconds)
1083         sleep(universe.categories["internal"]["time"].getfloat("increment"))
1084
1085         # increment the elapsed increment counter
1086         universe.categories["internal"]["counters"].set("elapsed", universe.categories["internal"]["counters"].getint("elapsed") + 1)
1087
1088 def reload_data():
1089         """Reload data into new persistent objects."""
1090         for user in universe.userlist[:]: user.reload()
1091
1092 def check_for_connection(listening_socket):
1093         """Check for a waiting connection and return a new user object."""
1094
1095         # try to accept a new connection
1096         try:
1097                 connection, address = listening_socket.accept()
1098         except:
1099                 return None
1100
1101         # note that we got one
1102         log("Connection from " + address[0], 2)
1103
1104         # disable blocking so we can proceed whether or not we can send/receive
1105         connection.setblocking(0)
1106
1107         # create a new user object
1108         user = User()
1109
1110         # associate this connection with it
1111         user.connection = connection
1112
1113         # set the user's ipa from the connection's ipa
1114         user.address = address[0]
1115
1116         # let the client know we WILL EOR
1117         user.send(IAC+WILL+EOR, raw=True)
1118         user.negotiation_pause = 2
1119
1120         # return the new user object
1121         return user
1122
1123 def get_menu(state, error=None, echoing=True, terminator="", choices=None):
1124         """Show the correct menu text to a user."""
1125
1126         # make sure we don't reuse a mutable sequence by default
1127         if choices is None: choices = {}
1128
1129         # begin with a telnet echo command sequence if needed
1130         message = get_echo_sequence(state, echoing)
1131
1132         # get the description or error text
1133         message += get_menu_description(state, error)
1134
1135         # get menu choices for the current state
1136         message += get_formatted_menu_choices(state, choices)
1137
1138         # try to get a prompt, if it was defined
1139         message += get_menu_prompt(state)
1140
1141         # throw in the default choice, if it exists
1142         message += get_formatted_default_menu_choice(state)
1143
1144         # display a message indicating if echo is off
1145         message += get_echo_message(state)
1146
1147         # tack on EOR or GA to indicate the prompt will not be followed by CRLF
1148         message += terminator
1149
1150         # return the assembly of various strings defined above
1151         return message
1152
1153 def menu_echo_on(state):
1154         """True if echo is on, false if it is off."""
1155         return universe.categories["menu"][state].getboolean("echo", True)
1156
1157 def get_echo_sequence(state, echoing):
1158         """Build the appropriate IAC WILL/WONT ECHO sequence as needed."""
1159
1160         # if the user has echo on and the menu specifies it should be turned
1161         # off, send: iac + will + echo + null
1162         if echoing and not menu_echo_on(state): return IAC+WILL+ECHO
1163
1164         # if echo is not set to off in the menu and the user curently has echo
1165         # off, send: iac + wont + echo + null
1166         elif not echoing and menu_echo_on(state): return IAC+WONT+ECHO
1167
1168         # default is not to send an echo control sequence at all
1169         else: return ""
1170
1171 def get_echo_message(state):
1172         """Return a message indicating that echo is off."""
1173         if menu_echo_on(state): return ""
1174         else: return "(won't echo) "
1175
1176 def get_default_menu_choice(state):
1177         """Return the default choice for a menu."""
1178         return universe.categories["menu"][state].get("default")
1179
1180 def get_formatted_default_menu_choice(state):
1181         """Default menu choice foratted for inclusion in a prompt string."""
1182         default_choice = get_default_menu_choice(state)
1183         if default_choice: return "[$(red)" + default_choice + "$(nrm)] "
1184         else: return ""
1185
1186 def get_menu_description(state, error):
1187         """Get the description or error text."""
1188
1189         # an error condition was raised by the handler
1190         if error:
1191
1192                 # try to get an error message matching the condition
1193                 # and current state
1194                 description = universe.categories["menu"][state].get("error_" + error)
1195                 if not description: description = "That is not a valid choice..."
1196                 description = "$(red)" + description + "$(nrm)"
1197
1198         # there was no error condition
1199         else:
1200
1201                 # try to get a menu description for the current state
1202                 description = universe.categories["menu"][state].get("description")
1203
1204         # return the description or error message
1205         if description: description += "$(eol)$(eol)"
1206         return description
1207
1208 def get_menu_prompt(state):
1209         """Try to get a prompt, if it was defined."""
1210         prompt = universe.categories["menu"][state].get("prompt")
1211         if prompt: prompt += " "
1212         return prompt
1213
1214 def get_menu_choices(user):
1215         """Return a dict of choice:meaning."""
1216         menu = universe.categories["menu"][user.state]
1217         create_choices = menu.get("create")
1218         if create_choices: choices = eval(create_choices)
1219         else: choices = {}
1220         ignores = []
1221         options = {}
1222         creates = {}
1223         for facet in menu.facets():
1224                 if facet.startswith("demand_") and not eval(universe.categories["menu"][user.state].get(facet)):
1225                         ignores.append(facet.split("_", 2)[1])
1226                 elif facet.startswith("create_"):
1227                         creates[facet] = facet.split("_", 2)[1]
1228                 elif facet.startswith("choice_"):
1229                         options[facet] = facet.split("_", 2)[1]
1230         for facet in creates.keys():
1231                 if not creates[facet] in ignores:
1232                         choices[creates[facet]] = eval(menu.get(facet))
1233         for facet in options.keys():
1234                 if not options[facet] in ignores:
1235                         choices[options[facet]] = menu.get(facet)
1236         return choices
1237
1238 def get_formatted_menu_choices(state, choices):
1239         """Returns a formatted string of menu choices."""
1240         choice_output = ""
1241         choice_keys = choices.keys()
1242         choice_keys.sort()
1243         for choice in choice_keys:
1244                 choice_output += "   [$(red)" + choice + "$(nrm)]  " + choices[choice] + "$(eol)"
1245         if choice_output: choice_output += "$(eol)"
1246         return choice_output
1247
1248 def get_menu_branches(state):
1249         """Return a dict of choice:branch."""
1250         branches = {}
1251         for facet in universe.categories["menu"][state].facets():
1252                 if facet.startswith("branch_"):
1253                         branches[facet.split("_", 2)[1]] = universe.categories["menu"][state].get(facet)
1254         return branches
1255
1256 def get_default_branch(state):
1257         """Return the default branch."""
1258         return universe.categories["menu"][state].get("branch")
1259
1260 def get_choice_branch(user, choice):
1261         """Returns the new state matching the given choice."""
1262         branches = get_menu_branches(user.state)
1263         if choice in branches.keys(): return branches[choice]
1264         elif choice in user.menu_choices.keys(): return get_default_branch(user.state)
1265         else: return ""
1266
1267 def get_menu_actions(state):
1268         """Return a dict of choice:branch."""
1269         actions = {}
1270         for facet in universe.categories["menu"][state].facets():
1271                 if facet.startswith("action_"):
1272                         actions[facet.split("_", 2)[1]] = universe.categories["menu"][state].get(facet)
1273         return actions
1274
1275 def get_default_action(state):
1276         """Return the default action."""
1277         return universe.categories["menu"][state].get("action")
1278
1279 def get_choice_action(user, choice):
1280         """Run any indicated script for the given choice."""
1281         actions = get_menu_actions(user.state)
1282         if choice in actions.keys(): return actions[choice]
1283         elif choice in user.menu_choices.keys(): return get_default_action(user.state)
1284         else: return ""
1285
1286 def handle_user_input(user):
1287         """The main handler, branches to a state-specific handler."""
1288
1289         # check to make sure the state is expected, then call that handler
1290         if "handler_" + user.state in globals():
1291                 exec("handler_" + user.state + "(user)")
1292         else:
1293                 generic_menu_handler(user)
1294
1295         # since we got input, flag that the menu/prompt needs to be redisplayed
1296         user.menu_seen = False
1297
1298         # if the user's client echo is off, send a blank line for aesthetics
1299         if user.echoing: user.received_newline = True
1300
1301 def generic_menu_handler(user):
1302         """A generic menu choice handler."""
1303
1304         # get a lower-case representation of the next line of input
1305         if user.input_queue:
1306                 choice = user.input_queue.pop(0)
1307                 if choice: choice = choice.lower()
1308         else: choice = ""
1309         if not choice: choice = get_default_menu_choice(user.state)
1310         if choice in user.menu_choices:
1311                 exec(get_choice_action(user, choice))
1312                 new_state = get_choice_branch(user, choice)
1313                 if new_state: user.state = new_state
1314         else: user.error = "default"
1315
1316 def handler_entering_account_name(user):
1317         """Handle the login account name."""
1318
1319         # get the next waiting line of input
1320         input_data = user.input_queue.pop(0)
1321
1322         # did the user enter anything?
1323         if input_data:
1324                 
1325                 # keep only the first word and convert to lower-case
1326                 name = input_data.lower()
1327
1328                 # fail if there are non-alphanumeric characters
1329                 if name != filter(lambda x: x>="0" and x<="9" or x>="a" and x<="z", name):
1330                         user.error = "bad_name"
1331
1332                 # if that account exists, time to request a password
1333                 elif name in universe.categories["account"]:
1334                         user.account = universe.categories["account"][name]
1335                         user.state = "checking_password"
1336
1337                 # otherwise, this could be a brand new user
1338                 else:
1339                         user.account = Element("account:" + name, universe)
1340                         user.account.set("name", name)
1341                         log("New user: " + name, 2)
1342                         user.state = "checking_new_account_name"
1343
1344         # if the user entered nothing for a name, then buhbye
1345         else:
1346                 user.state = "disconnecting"
1347
1348 def handler_checking_password(user):
1349         """Handle the login account password."""
1350
1351         # get the next waiting line of input
1352         input_data = user.input_queue.pop(0)
1353
1354         # does the hashed input equal the stored hash?
1355         if new_md5(user.account.get("name") + input_data).hexdigest() == user.account.get("passhash"):
1356
1357                 # if so, set the username and load from cold storage
1358                 if not user.replace_old_connections():
1359                         user.authenticate()
1360                         user.state = "main_utility"
1361
1362         # if at first your hashes don't match, try, try again
1363         elif user.password_tries < universe.categories["internal"]["limits"].getint("password_tries") - 1:
1364                 user.password_tries += 1
1365                 user.error = "incorrect"
1366
1367         # we've exceeded the maximum number of password failures, so disconnect
1368         else:
1369                 user.send("$(eol)$(red)Too many failed password attempts...$(nrm)$(eol)")
1370                 user.state = "disconnecting"
1371
1372 def handler_entering_new_password(user):
1373         """Handle a new password entry."""
1374
1375         # get the next waiting line of input
1376         input_data = user.input_queue.pop(0)
1377
1378         # make sure the password is strong--at least one upper, one lower and
1379         # one digit, seven or more characters in length
1380         if len(input_data) > 6 and len(filter(lambda x: x>="0" and x<="9", input_data)) and len(filter(lambda x: x>="A" and x<="Z", input_data)) and len(filter(lambda x: x>="a" and x<="z", input_data)):
1381
1382                 # hash and store it, then move on to verification
1383                 user.account.set("passhash",  new_md5(user.account.get("name") + input_data).hexdigest())
1384                 user.state = "verifying_new_password"
1385
1386         # the password was weak, try again if you haven't tried too many times
1387         elif user.password_tries < universe.categories["internal"]["limits"].getint("password_tries") - 1:
1388                 user.password_tries += 1
1389                 user.error = "weak"
1390
1391         # too many tries, so adios
1392         else:
1393                 user.send("$(eol)$(red)Too many failed password attempts...$(nrm)$(eol)")
1394                 user.account.destroy()
1395                 user.state = "disconnecting"
1396
1397 def handler_verifying_new_password(user):
1398         """Handle the re-entered new password for verification."""
1399
1400         # get the next waiting line of input
1401         input_data = user.input_queue.pop(0)
1402
1403         # hash the input and match it to storage
1404         if new_md5(user.account.get("name") + input_data).hexdigest() == user.account.get("passhash"):
1405                 user.authenticate()
1406
1407                 # the hashes matched, so go active
1408                 if not user.replace_old_connections(): user.state = "main_utility"
1409
1410         # go back to entering the new password as long as you haven't tried
1411         # too many times
1412         elif user.password_tries < universe.categories["internal"]["limits"].getint("password_tries") - 1:
1413                 user.password_tries += 1
1414                 user.error = "differs"
1415                 user.state = "entering_new_password"
1416
1417         # otherwise, sayonara
1418         else:
1419                 user.send("$(eol)$(red)Too many failed password attempts...$(nrm)$(eol)")
1420                 user.account.destroy()
1421                 user.state = "disconnecting"
1422
1423 def handler_active(user):
1424         """Handle input for active users."""
1425
1426         # get the next waiting line of input
1427         input_data = user.input_queue.pop(0)
1428
1429         # is there input?
1430         if input_data:
1431
1432                 # split out the command (first word) and parameters (everything else)
1433                 if input_data.find(" ") > 0:
1434                         command_name, parameters = input_data.split(" ", 1)
1435                 else:
1436                         command_name = input_data
1437                         parameters = ""
1438
1439                 # lowercase the command
1440                 command_name = command_name.lower()
1441
1442                 # the command matches a command word for which we have data
1443                 if command_name in universe.categories["command"]:
1444                         command = universe.categories["command"][command_name]
1445                 else: command = None
1446
1447                 # if it's allowed, do it
1448                 if user.avatar.can_run(command): exec(command.get("action"))
1449
1450                 # otherwise, give an error
1451                 elif command_name: command_error(user.avatar, input_data)
1452
1453         # if no input, just idle back with a prompt
1454         else: user.send("", just_prompt=True)
1455         
1456 def command_halt(actor, parameters):
1457         """Halt the world."""
1458         if actor.owner:
1459
1460                 # see if there's a message or use a generic one
1461                 if parameters: message = "Halting: " + parameters
1462                 else: message = "User " + actor.owner.account.get("name") + " halted the world."
1463
1464                 # let everyone know
1465                 broadcast(message, add_prompt=False)
1466                 log(message, 8)
1467
1468                 # set a flag to terminate the world
1469                 universe.terminate_world = True
1470
1471 def command_reload(actor):
1472         """Reload all code modules, configs and data."""
1473         if actor.owner:
1474
1475                 # let the user know and log
1476                 actor.send("Reloading all code modules, configs and data.")
1477                 log("User " + actor.owner.account.get("name") + " reloaded the world.", 8)
1478
1479                 # set a flag to reload
1480                 universe.reload_modules = True
1481
1482 def command_quit(actor):
1483         """Leave the world and go back to the main menu."""
1484         if actor.owner:
1485                 actor.owner.deactivate_avatar()
1486                 actor.owner.state = "main_utility"
1487
1488 def command_help(actor, parameters):
1489         """List available commands and provide help for commands."""
1490
1491         # did the user ask for help on a specific command word?
1492         if parameters and actor.owner:
1493
1494                 # is the command word one for which we have data?
1495                 if parameters in universe.categories["command"]:
1496                         command = universe.categories["command"][parameters]
1497                 else: command = None
1498
1499                 # only for allowed commands
1500                 if actor.can_run(command):
1501
1502                         # add a description if provided
1503                         description = command.get("description")
1504                         if not description:
1505                                 description = "(no short description provided)"
1506                         if command.getboolean("administrative"): output = "$(red)"
1507                         else: output = "$(grn)"
1508                         output += parameters + "$(nrm) - " + description + "$(eol)$(eol)"
1509
1510                         # add the help text if provided
1511                         help_text = command.get("help")
1512                         if not help_text:
1513                                 help_text = "No help is provided for this command."
1514                         output += help_text
1515
1516                 # no data for the requested command word
1517                 else:
1518                         output = "That is not an available command."
1519
1520         # no specific command word was indicated
1521         else:
1522
1523                 # give a sorted list of commands with descriptions if provided
1524                 output = "These are the commands available to you:$(eol)$(eol)"
1525                 sorted_commands = universe.categories["command"].keys()
1526                 sorted_commands.sort()
1527                 for item in sorted_commands:
1528                         command = universe.categories["command"][item]
1529                         if actor.can_run(command):
1530                                 description = command.get("description")
1531                                 if not description:
1532                                         description = "(no short description provided)"
1533                                 if command.getboolean("administrative"): output += "   $(red)"
1534                                 else: output += "   $(grn)"
1535                                 output += item + "$(nrm) - " + description + "$(eol)"
1536                 output += "$(eol)Enter \"help COMMAND\" for help on a command named \"COMMAND\"."
1537
1538         # send the accumulated output to the user
1539         actor.send(output)
1540
1541 def command_move(actor, parameters):
1542         """Move the avatar in a given direction."""
1543         if parameters in universe.contents[actor.get("location")].portals():
1544                 actor.move_direction(parameters)
1545         else: actor.send("You cannot go that way.")
1546
1547 def command_look(actor, parameters):
1548         """Look around."""
1549         if parameters: actor.send("You can't look at or in anything yet.")
1550         else: actor.look_at(actor.get("location"))
1551
1552 def command_say(actor, parameters):
1553         """Speak to others in the same room."""
1554
1555         # check for replacement macros
1556         if replace_macros(actor.owner, parameters, True) != parameters:
1557                 actor.send("You cannot speak $_(replacement macros).")
1558
1559         # the user entered a message
1560         elif parameters:
1561
1562                 # get rid of quote marks on the ends of the message and
1563                 # capitalize the first letter
1564                 message = parameters.strip("\"'`").capitalize()
1565
1566                 # a dictionary of punctuation:action pairs
1567                 actions = {}
1568                 for facet in universe.categories["internal"]["language"].facets():
1569                         if facet.startswith("punctuation_"):
1570                                 action = facet.split("_")[1]
1571                                 for mark in universe.categories["internal"]["language"].getlist(facet):
1572                                                 actions[mark] = action
1573
1574                 # match the punctuation used, if any, to an action
1575                 default_punctuation = universe.categories["internal"]["language"].get("default_punctuation")
1576                 action = actions[default_punctuation]
1577                 for mark in actions.keys():
1578                         if message.endswith(mark) and mark != default_punctuation:
1579                                 action = actions[mark]
1580                                 break
1581
1582                 # if the action is default and there is no mark, add one
1583                 if action == actions[default_punctuation] and not message.endswith(default_punctuation):
1584                         message += default_punctuation
1585
1586                 # capitalize a list of words within the message
1587                 capitalize_words = universe.categories["internal"]["language"].getlist("capitalize_words")
1588                 for word in capitalize_words:
1589                         message = message.replace(" " + word + " ", " " + word.capitalize() + " ")
1590
1591                 # tell the room
1592                 actor.echo_to_location(actor.get("name") + " " + action + "s, \"" + message + "\"")
1593                 actor.send("You " + action + ", \"" + message + "\"")
1594
1595         # there was no message
1596         else:
1597                 actor.send("What do you want to say?")
1598
1599 def command_show(actor, parameters):
1600         """Show program data."""
1601         message = ""
1602         if parameters.find(" ") < 1:
1603                 if parameters == "time":
1604                         message = universe.categories["internal"]["counters"].get("elapsed") + " increments elapsed since the world was created."
1605                 elif parameters == "categories":
1606                         message = "These are the element categories:$(eol)"
1607                         categories = universe.categories.keys()
1608                         categories.sort()
1609                         for category in categories: message += "$(eol)   $(grn)" + category + "$(nrm)"
1610                 elif parameters == "files":
1611                         message = "These are the current files containing the universe:$(eol)"
1612                         filenames = universe.files.keys()
1613                         filenames.sort()
1614                         for filename in filenames: message += "$(eol)   $(grn)" + filename + "$(nrm)"
1615                 else: message = ""
1616         else:
1617                 arguments = parameters.split()
1618                 if arguments[0] == "category":
1619                         if arguments[1] in universe.categories:
1620                                 message = "These are the elements in the \"" + arguments[1] + "\" category:$(eol)"
1621                                 elements = universe.categories[arguments[1]].keys()
1622                                 elements.sort()
1623                                 for element in elements:
1624                                         message += "$(eol)   $(grn)" + universe.categories[arguments[1]][element].key + "$(nrm)"
1625                 elif arguments[0] == "element":
1626                         if arguments[1] in universe.contents:
1627                                 message = "These are the properties of the \"" + arguments[1] + "\" element:$(eol)"
1628                                 element = universe.contents[arguments[1]]
1629                                 facets = element.facets()
1630                                 facets.sort()
1631                                 for facet in facets:
1632                                         message += "$(eol)   $(grn)" + facet + ": $(red)" + escape_macros(element.get(facet)) + "$(nrm)"
1633                 elif arguments[0] == "result":
1634                         if len(arguments) > 1:
1635                                 try:
1636                                         message = repr(eval(" ".join(arguments[1:])))
1637                                 except:
1638                                         message = "Your expression raised an exception!"
1639                 elif arguments[0] == "log":
1640                         if match("^\d+$", arguments[1]) and int(arguments[1]) > 0:
1641                                 linecount = int(arguments[1])
1642                                 if linecount > len(universe.loglines): linecount = len(universe.loglist)
1643                                 message = "There are " + str(len(universe.loglist)) + " log lines in memory."
1644                                 message += " The most recent " + str(linecount) + " lines are:$(eol)$(eol)"
1645                                 for line in universe.loglist[-linecount:]:
1646                                         message += "   " + line + "$(eol)"
1647                         else: message = "\"" + arguments[1] + "\" is not a positive integer greater than 0."
1648         if not message:
1649                 if parameters: message = "I don't know what \"" + parameters + "\" is."
1650                 else: message = "What do you want to show?"
1651         actor.send(message)
1652
1653 def command_create(actor, parameters):
1654         """Create an element if it does not exist."""
1655         if not parameters: message = "You must at least specify an element to create."
1656         elif not actor.owner: message = ""
1657         else:
1658                 arguments = parameters.split()
1659                 if len(arguments) == 1: arguments.append("")
1660                 if len(arguments) == 2:
1661                         element, filename = arguments
1662                         if element in universe.contents: message = "The \"" + element + "\" element already exists."
1663                         else:
1664                                 message = "You create \"" + element + "\" within the universe."
1665                                 logline = actor.owner.account.get("name") + " created an element: " + element
1666                                 if filename:
1667                                         logline += " in file " + filename
1668                                         if filename not in universe.files:
1669                                                 message += " Warning: \"" + filename + "\" is not yet included in any other file and will not be read on startup unless this is remedied."
1670                                 Element(element, universe, filename)
1671                                 log(logline, 6)
1672                 elif len(arguments) > 2: message = "You can only specify an element and a filename."
1673         actor.send(message)
1674
1675 def command_destroy(actor, parameters):
1676         """Destroy an element if it exists."""
1677         if actor.owner:
1678                 if not parameters: message = "You must specify an element to destroy."
1679                 else:
1680                         if parameters not in universe.contents: message = "The \"" + parameters + "\" element does not exist."
1681                         else:
1682                                 universe.contents[parameters].destroy()
1683                                 message = "You destroy \"" + parameters + "\" within the universe."
1684                                 log(actor.owner.account.get("name") + " destroyed an element: " + parameters, 6)
1685                 actor.send(message)
1686
1687 def command_set(actor, parameters):
1688         """Set a facet of an element."""
1689         if not parameters: message = "You must specify an element, a facet and a value."
1690         else:
1691                 arguments = parameters.split(" ", 2)
1692                 if len(arguments) == 1: message = "What facet of element \"" + arguments[0] + "\" would you like to set?"
1693                 elif len(arguments) == 2: message = "What value would you like to set for the \"" + arguments[1] + "\" facet of the \"" + arguments[0] + "\" element?"
1694                 else:
1695                         element, facet, value = arguments
1696                         if element not in universe.contents: message = "The \"" + element + "\" element does not exist."
1697                         else:
1698                                 universe.contents[element].set(facet, value)
1699                                 message = "You have successfully (re)set the \"" + facet + "\" facet of element \"" + element + "\". Try \"show element " + element + "\" for verification."
1700         actor.send(message)
1701
1702 def command_delete(actor, parameters):
1703         """Delete a facet from an element."""
1704         if not parameters: message = "You must specify an element and a facet."
1705         else:
1706                 arguments = parameters.split(" ")
1707                 if len(arguments) == 1: message = "What facet of element \"" + arguments[0] + "\" would you like to delete?"
1708                 elif len(arguments) != 2: message = "You may only specify an element and a facet."
1709                 else:
1710                         element, facet = arguments
1711                         if element not in universe.contents: message = "The \"" + element + "\" element does not exist."
1712                         elif facet not in universe.contents[element].facets(): message = "The \"" + element + "\" element has no \"" + facet + "\" facet."
1713                         else:
1714                                 universe.contents[element].remove_facet(facet)
1715                                 message = "You have successfully deleted the \"" + facet + "\" facet of element \"" + element + "\". Try \"show element " + element + "\" for verification."
1716         actor.send(message)
1717
1718 def command_error(actor, input_data):
1719         """Generic error for an unrecognized command word."""
1720
1721         # 90% of the time use a generic error
1722         if randrange(10):
1723                 message = "I'm not sure what \"" + input_data + "\" means..."
1724
1725         # 10% of the time use the classic diku error
1726         else:
1727                 message = "Arglebargle, glop-glyf!?!"
1728
1729         # send the error message
1730         actor.send(message)
1731
1732 # if there is no universe, create an empty one
1733 if not "universe" in locals(): universe = Universe()
1734