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