01b914293971b7b412a08d391eb77a3444e794f2
[mudpy.git] / mudpy.py
1 """Core objects for the mudpy engine."""
2
3 # Copyright (c) 2005, 2006 Jeremy Stanley <fungi@yuggoth.org>. All rights
4 # reserved. Licensed per terms in the LICENSE file distributed with this
5 # 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.menu_choices = {}
512                 self.menu_seen = False
513                 self.negotiation_pause = 0
514                 self.output_queue = []
515                 self.partial_input = ""
516                 self.password_tries = 0
517                 self.received_newline = True
518                 self.state = "initial"
519                 self.terminator = IAC+GA
520
521         def quit(self):
522                 """Log, close the connection and remove."""
523                 if self.account: name = self.account.get("name")
524                 else: name = ""
525                 if name: message = "User " + name
526                 else: message = "An unnamed user"
527                 message += " logged out."
528                 log(message, 2)
529                 self.deactivate_avatar()
530                 self.connection.close()
531                 self.remove()
532
533         def reload(self):
534                 """Save, load a new user and relocate the connection."""
535
536                 # get out of the list
537                 self.remove()
538
539                 # create a new user object
540                 new_user = User()
541
542                 # set everything equivalent
543                 for attribute in vars(self).keys():
544                         exec("new_user." + attribute + " = self." + attribute)
545
546                 # the avatar needs a new owner
547                 if new_user.avatar: new_user.avatar.owner = new_user
548
549                 # add it to the list
550                 universe.userlist.append(new_user)
551
552                 # get rid of the old user object
553                 del(self)
554
555         def replace_old_connections(self):
556                 """Disconnect active users with the same name."""
557
558                 # the default return value
559                 return_value = False
560
561                 # iterate over each user in the list
562                 for old_user in universe.userlist:
563
564                         # the name is the same but it's not us
565                         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:
566
567                                 # make a note of it
568                                 log("User " + self.account.get("name") + " reconnected--closing old connection to " + old_user.address + ".", 2)
569                                 old_user.send("$(eol)$(red)New connection from " + self.address + ". Terminating old connection...$(nrm)$(eol)", flush=True, add_prompt=False)
570
571                                 # close the old connection
572                                 old_user.connection.close()
573
574                                 # replace the old connection with this one
575                                 old_user.send("$(eol)$(red)Taking over old connection from " + old_user.address + ".$(nrm)")
576                                 old_user.connection = self.connection
577                                 old_user.last_address = old_user.address
578                                 old_user.address = self.address
579
580                                 # may need to tell the new connection to echo
581                                 if old_user.echoing:
582                                         old_user.send(get_echo_sequence(old_user.state, self.echoing), raw=True)
583
584                                 # take this one out of the list and delete
585                                 self.remove()
586                                 del(self)
587                                 return_value = True
588                                 break
589
590                 # true if an old connection was replaced, false if not
591                 return return_value
592
593         def authenticate(self):
594                 """Flag the user as authenticated and disconnect duplicates."""
595                 if not self.state is "authenticated":
596                         log("User " + self.account.get("name") + " logged in.", 2)
597                         self.authenticated = True
598                         if self.account.subkey in universe.categories["internal"]["limits"].getlist("default_admins"):
599                                 self.account.set("administrator", "True")
600
601         def show_menu(self):
602                 """Send the user their current menu."""
603                 if not self.menu_seen:
604                         self.menu_choices = get_menu_choices(self)
605                         self.send(get_menu(self.state, self.error, self.echoing, self.terminator, self.menu_choices), "")
606                         self.menu_seen = True
607                         self.error = False
608                         self.adjust_echoing()
609
610         def adjust_echoing(self):
611                 """Adjust echoing to match state menu requirements."""
612                 if self.echoing and not menu_echo_on(self.state): self.echoing = False
613                 elif not self.echoing and menu_echo_on(self.state): self.echoing = True
614
615         def remove(self):
616                 """Remove a user from the list of connected users."""
617                 universe.userlist.remove(self)
618
619         def send(self, output, eol="$(eol)", raw=False, flush=False, add_prompt=True, just_prompt=False):
620                 """Send arbitrary text to a connected user."""
621
622                 # unless raw mode is on, clean it up all nice and pretty
623                 if not raw:
624
625                         # strip extra $(eol) off if present
626                         while output.startswith("$(eol)"): output = output[6:]
627                         while output.endswith("$(eol)"): output = output[:-6]
628                         extra_lines = output.find("$(eol)$(eol)$(eol)")
629                         while extra_lines > -1:
630                                 output = output[:extra_lines] + output[extra_lines+6:]
631                                 extra_lines = output.find("$(eol)$(eol)$(eol)")
632
633                         # we'll take out GA or EOR and add them back on the end
634                         if output.endswith(IAC+GA) or output.endswith(IAC+EOR):
635                                 terminate = True
636                                 output = output[:-2]
637                         else: terminate = False
638
639                         # start with a newline, append the message, then end
640                         # with the optional eol string passed to this function
641                         # and the ansi escape to return to normal text
642                         if not just_prompt:
643                                 if not self.output_queue or not self.output_queue[-1].endswith("\r\n"):
644                                         output = "$(eol)$(eol)" + output
645                                 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"):
646                                         output = "$(eol)" + output
647                         output += eol + chr(27) + "[0m"
648
649                         # tack on a prompt if active
650                         if self.state == "active":
651                                 if not just_prompt: output += "$(eol)"
652                                 if add_prompt:
653                                         output += "> "
654                                         mode = self.avatar.get("mode")
655                                         if mode: output += "(" + mode + ") "
656
657                         # find and replace macros in the output
658                         output = replace_macros(self, output)
659
660                         # wrap the text at 79 characters
661                         output = wrap_ansi_text(output, 79)
662
663                         # tack the terminator back on
664                         if terminate: output += self.terminator
665
666                 # drop the output into the user's output queue
667                 self.output_queue.append(output)
668
669                 # if this is urgent, flush all pending output
670                 if flush: self.flush()
671
672         def pulse(self):
673                 """All the things to do to the user per increment."""
674
675                 # if the world is terminating, disconnect
676                 if universe.terminate_flag:
677                         self.state = "disconnecting"
678                         self.menu_seen = False
679
680                 # if output is paused, decrement the counter
681                 if self.state == "initial":
682                         if self.negotiation_pause: self.negotiation_pause -= 1
683                         else: self.state = "entering_account_name"
684
685                 # show the user a menu as needed
686                 elif not self.state == "active": self.show_menu()
687
688                 # flush any pending output in teh queue
689                 self.flush()
690
691                 # disconnect users with the appropriate state
692                 if self.state == "disconnecting": self.quit()
693
694                 # check for input and add it to the queue
695                 self.enqueue_input()
696
697                 # there is input waiting in the queue
698                 if self.input_queue:
699                         handle_user_input(self)
700
701         def flush(self):
702                 """Try to send the last item in the queue and remove it."""
703                 if self.output_queue:
704                         if self.received_newline:
705                                 self.received_newline = False
706                                 if self.output_queue[0].startswith("\r\n"):
707                                         self.output_queue[0] = self.output_queue[0][2:]
708                         try:
709                                 self.connection.send(self.output_queue[0])
710                                 del self.output_queue[0]
711                         except:
712                                 pass
713
714
715         def enqueue_input(self):
716                 """Process and enqueue any new input."""
717
718                 # check for some input
719                 try:
720                         input_data = self.connection.recv(1024)
721                 except:
722                         input_data = ""
723
724                 # we got something
725                 if input_data:
726
727                         # tack this on to any previous partial
728                         self.partial_input += input_data
729
730                         # reply to and remove any IAC negotiation codes
731                         self.negotiate_telnet_options()
732
733                         # separate multiple input lines
734                         new_input_lines = self.partial_input.split("\n")
735
736                         # if input doesn't end in a newline, replace the
737                         # held partial input with the last line of it
738                         if not self.partial_input.endswith("\n"):
739                                 self.partial_input = new_input_lines.pop()
740
741                         # otherwise, chop off the extra null input and reset
742                         # the held partial input
743                         else:
744                                 new_input_lines.pop()
745                                 self.partial_input = ""
746
747                         # iterate over the remaining lines
748                         for line in new_input_lines:
749
750                                 # remove a trailing carriage return
751                                 if line.endswith("\r"): line = line.rstrip("\r")
752
753                                 # log non-printable characters remaining
754                                 removed = filter(lambda x: (x < " " or x > "~"), line)
755                                 if removed:
756                                         logline = "Non-printable characters from "
757                                         if self.account and self.account.get("name"): logline += self.account.get("name") + ": "
758                                         else: logline += "unknown user: "
759                                         logline += repr(removed)
760                                         log(logline, 4)
761
762                                 # filter out non-printables
763                                 line = filter(lambda x: " " <= x <= "~", line)
764
765                                 # strip off extra whitespace
766                                 line = line.strip()
767
768                                 # put on the end of the queue
769                                 self.input_queue.append(line)
770
771         def negotiate_telnet_options(self):
772                 """Reply to/remove partial_input telnet negotiation options."""
773
774                 # start at the begining of the input
775                 position = 0
776
777                 # make a local copy to play with
778                 text = self.partial_input
779
780                 # as long as we haven't checked it all
781                 while position < len(text):
782
783                         # jump to the first IAC you find
784                         position = text.find(IAC, position)
785
786                         # if there wasn't an IAC in the input, skip to the end
787                         if position < 0: position = len(text)
788
789                         # replace a double (literal) IAC if there's an LF later
790                         elif len(text) > position+1 and text[position+1] == IAC:
791                                 if text.find("\n", position) > 0: text = text.replace(IAC+IAC, IAC)
792                                 else: position += 1
793                                 position += 1
794
795                         # this must be an option negotiation
796                         elif len(text) > position+2 and text[position+1] in (DO, DONT, WILL, WONT):
797
798                                 negotiation = text[position+1:position+3]
799
800                                 # if we turned echo off, ignore the confirmation
801                                 if not self.echoing and negotiation == DO+ECHO: pass
802
803                                 # allow LINEMODE
804                                 elif negotiation == WILL+LINEMODE: self.send(IAC+DO+LINEMODE, raw=True)
805
806                                 # if the client likes EOR instead of GA, make a note of it
807                                 elif negotiation == DO+EOR: self.terminator = IAC+EOR
808                                 elif negotiation == DONT+EOR and self.terminator == IAC+EOR:
809                                         self.terminator = IAC+GA
810
811                                 # if the client doesn't want GA, oblige
812                                 elif negotiation == DO+SGA and self.terminator == IAC+GA:
813                                         self.terminator = ""
814                                         self.send(IAC+WILL+SGA, raw=True)
815
816                                 # we don't want to allow anything else
817                                 elif text[position+1] == DO: self.send(IAC+WONT+text[position+2], raw=True)
818                                 elif text[position+1] == WILL: self.send(IAC+DONT+text[position+2], raw=True)
819
820                                 # strip the negotiation from the input
821                                 text = text.replace(text[position:position+3], "")
822
823                         # get rid of IAC SB .* IAC SE
824                         elif len(text) > position+4 and text[position:position+2] == IAC+SB:
825                                 end_subnegotiation = text.find(IAC+SE, position)
826                                 if end_subnegotiation > 0: text = text[:position] + text[end_subnegotiation+2:]
827                                 else: position += 1
828
829                         # otherwise, strip out a two-byte IAC command
830                         elif len(text) > position+2: text = text.replace(text[position:position+2], "")
831
832                         # and this means we got the begining of an IAC
833                         else: position += 1
834
835                 # replace the input with our cleaned-up text
836                 self.partial_input = text
837
838         def new_avatar(self):
839                 """Instantiate a new, unconfigured avatar for this user."""
840                 counter = 0
841                 while "avatar:" + self.account.get("name") + ":" + str(counter) in universe.categories["actor"].keys(): counter += 1
842                 self.avatar = Element("actor:avatar:" + self.account.get("name") + ":" + str(counter), universe)
843                 self.avatar.append("inherit", "archetype:avatar")
844                 self.account.append("avatars", self.avatar.key)
845
846         def delete_avatar(self, avatar):
847                 """Remove an avatar from the world and from the user's list."""
848                 if self.avatar is universe.contents[avatar]: self.avatar = None
849                 universe.contents[avatar].destroy()
850                 avatars = self.account.getlist("avatars")
851                 avatars.remove(avatar)
852                 self.account.set("avatars", avatars)
853
854         def activate_avatar_by_index(self, index):
855                 """Enter the world with a particular indexed avatar."""
856                 self.avatar = universe.contents[self.account.getlist("avatars")[index]]
857                 self.avatar.owner = self
858                 self.state = "active"
859                 self.avatar.go_home()
860
861         def deactivate_avatar(self):
862                 """Have the active avatar leave the world."""
863                 if self.avatar:
864                         current = self.avatar.get("location")
865                         if current:
866                                 self.avatar.set("default_location", current)
867                                 self.avatar.echo_to_location("You suddenly wonder where " + self.avatar.get("name") + " went.")
868                                 del universe.contents[current].contents[self.avatar.key]
869                                 self.avatar.remove_facet("location")
870                         self.avatar.owner = None
871                         self.avatar = None
872
873         def destroy(self):
874                 """Destroy the user and associated avatars."""
875                 for avatar in self.account.getlist("avatars"): self.delete_avatar(avatar)
876                 self.account.destroy()
877
878         def list_avatar_names(self):
879                 """List names of assigned avatars."""
880                 return [ universe.contents[avatar].get("name") for avatar in self.account.getlist("avatars") ]
881
882 def makelist(value):
883         """Turn string into list type."""
884         if value[0] + value[-1] == "[]": return eval(value)
885         else: return [ value ]
886
887 def makedict(value):
888         """Turn string into dict type."""
889         if value[0] + value[-1] == "{}": return eval(value)
890         elif value.find(":") > 0: return eval("{" + value + "}")
891         else: return { value: None }
892
893 def broadcast(message, add_prompt=True):
894         """Send a message to all connected users."""
895         for each_user in universe.userlist: each_user.send("$(eol)" + message, add_prompt=add_prompt)
896
897 def log(message, level=0):
898         """Log a message."""
899
900         # a couple references we need
901         file_name = universe.categories["internal"]["logging"].get("file")
902         max_log_lines = universe.categories["internal"]["logging"].getint("max_log_lines")
903         syslog_name = universe.categories["internal"]["logging"].get("syslog")
904         timestamp = asctime()[4:19]
905
906         # turn the message into a list of lines
907         lines = filter(lambda x: x!="", [(x.rstrip()) for x in message.split("\n")])
908
909         # send the timestamp and line to a file
910         if file_name:
911                 if not isabs(file_name):
912                         file_name = path_join(universe.startdir, file_name)
913                 file_descriptor = file(file_name, "a")
914                 for line in lines: file_descriptor.write(timestamp + " " + line + "\n")
915                 file_descriptor.flush()
916                 file_descriptor.close()
917
918         # send the timestamp and line to standard output
919         if universe.categories["internal"]["logging"].getboolean("stdout"):
920                 for line in lines: print(timestamp + " " + line)
921
922         # send the line to the system log
923         if syslog_name:
924                 openlog(syslog_name, LOG_PID, LOG_INFO | LOG_DAEMON)
925                 for line in lines: syslog(line)
926                 closelog()
927
928         # display to connected administrators
929         for user in universe.userlist:
930                 if user.state == "active" and user.account.getboolean("administrator") and user.account.getint("loglevel") <= level:
931                         # iterate over every line in the message
932                         full_message = ""
933                         for line in lines:
934                                 full_message += "$(bld)$(red)" + timestamp + " " + line + "$(nrm)$(eol)"
935                         user.send(full_message, flush=True)
936
937         # add to the recent log list
938         for line in lines:
939                 while 0 < len(universe.loglines) >= max_log_lines: del universe.loglines[0]
940                 universe.loglines.append((level, timestamp + " " + line))
941
942 def get_loglines(level, start, stop):
943         """Return a specific range of loglines filtered by level."""
944
945         # filter the log lines
946         loglines = filter(lambda x: x[0]>=level, universe.loglines)
947
948         # we need these in several places
949         total_count = str(len(universe.loglines))
950         filtered_count = len(loglines)
951
952         # don't proceed if there are no lines
953         if filtered_count:
954
955                 # can't start before the begining or at the end
956                 if start > filtered_count: start = filtered_count
957                 if start < 1: start = 1
958
959                 # can't stop before we start
960                 if stop > start: stop = start
961                 elif stop < 1: stop = 1
962
963                 # some preamble
964                 message = "There are " + str(total_count)
965                 message += " log lines in memory and " + str(filtered_count)
966                 message += " at or above level " + str(level) + "."
967                 message += " The matching lines from " + str(stop) + " to "
968                 message += str(start) + " are:$(eol)$(eol)"
969
970                 # add the text from the selected lines
971                 if stop > 1: range_lines = loglines[-start:-(stop-1)]
972                 else: range_lines = loglines[-start:]
973                 for line in range_lines:
974                         message += "   (" + str(line[0]) + ") " + line[1] + "$(eol)"
975
976         # there were no lines
977         else:
978                 message = "None of the " + str(total_count)
979                 message += " lines in memory matches your request."
980
981         # pass it back
982         return message
983
984 def wrap_ansi_text(text, width):
985         """Wrap text with arbitrary width while ignoring ANSI colors."""
986
987         # the current position in the entire text string, including all
988         # characters, printable or otherwise
989         absolute_position = 0
990
991         # the current text position relative to the begining of the line,
992         # ignoring color escape sequences
993         relative_position = 0
994
995         # whether the current character is part of a color escape sequence
996         escape = False
997
998         # iterate over each character from the begining of the text
999         for each_character in text:
1000
1001                 # the current character is the escape character
1002                 if each_character == chr(27):
1003                         escape = True
1004
1005                 # the current character is within an escape sequence
1006                 elif escape:
1007
1008                         # the current character is m, which terminates the
1009                         # current escape sequence
1010                         if each_character == "m":
1011                                 escape = False
1012
1013                 # the current character is a newline, so reset the relative
1014                 # position (start a new line)
1015                 elif each_character == "\n":
1016                         relative_position = 0
1017
1018                 # the current character meets the requested maximum line width,
1019                 # so we need to backtrack and find a space at which to wrap
1020                 elif relative_position == width:
1021
1022                         # distance of the current character examined from the
1023                         # relative position
1024                         wrap_offset = 0
1025
1026                         # count backwards until we find a space
1027                         while text[absolute_position - wrap_offset] != " ":
1028                                 wrap_offset += 1
1029
1030                         # insert an eol in place of the space
1031                         text = text[:absolute_position - wrap_offset] + "\r\n" + text[absolute_position - wrap_offset + 1:]
1032
1033                         # increase the absolute position because an eol is two
1034                         # characters but the space it replaced was only one
1035                         absolute_position += 1
1036
1037                         # now we're at the begining of a new line, plus the
1038                         # number of characters wrapped from the previous line
1039                         relative_position = wrap_offset
1040
1041                 # as long as the character is not a carriage return and the
1042                 # other above conditions haven't been met, count it as a
1043                 # printable character
1044                 elif each_character != "\r":
1045                         relative_position += 1
1046
1047                 # increase the absolute position for every character
1048                 absolute_position += 1
1049
1050         # return the newly-wrapped text
1051         return text
1052
1053 def weighted_choice(data):
1054         """Takes a dict weighted by value and returns a random key."""
1055
1056         # this will hold our expanded list of keys from the data
1057         expanded = []
1058
1059         # create thee expanded list of keys
1060         for key in data.keys():
1061                 for count in range(data[key]):
1062                         expanded.append(key)
1063
1064         # return one at random
1065         return choice(expanded)
1066
1067 def random_name():
1068         """Returns a random character name."""
1069
1070         # the vowels and consonants needed to create romaji syllables
1071         vowels = [ "a", "i", "u", "e", "o" ]
1072         consonants = ["'", "k", "z", "s", "sh", "z", "j", "t", "ch", "ts", "d", "n", "h", "f", "m", "y", "r", "w" ]
1073
1074         # this dict will hold our weighted list of syllables
1075         syllables = {}
1076
1077         # generate the list with an even weighting
1078         for consonant in consonants:
1079                 for vowel in vowels:
1080                         syllables[consonant + vowel] = 1
1081
1082         # we'll build the name into this string
1083         name = ""
1084
1085         # create a name of random length from the syllables
1086         for syllable in range(randrange(2, 6)):
1087                 name += weighted_choice(syllables)
1088
1089         # strip any leading quotemark, capitalize and return the name
1090         return name.strip("'").capitalize()
1091
1092 def replace_macros(user, text, is_input=False):
1093         """Replaces macros in text output."""
1094
1095         # loop until broken
1096         while True:
1097
1098                 # third person pronouns
1099                 pronouns = {
1100                         "female": { "obj": "her", "pos": "hers", "sub": "she" },
1101                         "male": { "obj": "him", "pos": "his", "sub": "he" },
1102                         "neuter": { "obj": "it", "pos": "its", "sub": "it" }
1103                         }
1104
1105                 # a dict of replacement macros
1106                 macros = {
1107                         "$(eol)": "\r\n",
1108                         "$(bld)": chr(27) + "[1m",
1109                         "$(nrm)": chr(27) + "[0m",
1110                         "$(blk)": chr(27) + "[30m",
1111                         "$(blu)": chr(27) + "[34m",
1112                         "$(cyn)": chr(27) + "[36m",
1113                         "$(grn)": chr(27) + "[32m",
1114                         "$(mgt)": chr(27) + "[35m",
1115                         "$(red)": chr(27) + "[31m",
1116                         "$(yel)": chr(27) + "[33m",
1117                         }
1118
1119                 # add dynamic macros where possible
1120                 if user.account:
1121                         account_name = user.account.get("name")
1122                         if account_name:
1123                                 macros["$(account)"] = account_name
1124                 if user.avatar:
1125                         avatar_gender = user.avatar.get("gender")
1126                         if avatar_gender:
1127                                 macros["$(tpop)"] = pronouns[avatar_gender]["obj"]
1128                                 macros["$(tppp)"] = pronouns[avatar_gender]["pos"]
1129                                 macros["$(tpsp)"] = pronouns[avatar_gender]["sub"]
1130
1131                 # find and replace per the macros dict
1132                 macro_start = text.find("$(")
1133                 if macro_start == -1: break
1134                 macro_end = text.find(")", macro_start) + 1
1135                 macro = text[macro_start:macro_end]
1136                 if macro in macros.keys():
1137                         text = text.replace(macro, macros[macro])
1138
1139                 # if we get here, log and replace it with null
1140                 else:
1141                         text = text.replace(macro, "")
1142                         if not is_input:
1143                                 log("Unexpected replacement macro " + macro + " encountered.", 6)
1144
1145         # replace the look-like-a-macro sequence
1146         text = text.replace("$_(", "$(")
1147
1148         return text
1149
1150 def escape_macros(text):
1151         """Escapes replacement macros in text."""
1152         return text.replace("$(", "$_(")
1153
1154 def first_word(text, separator=" "):
1155         """Returns a tuple of the first word and the rest."""
1156         if text:
1157                 if text.find(separator) > 0: return text.split(separator, 1)
1158                 else: return text, ""
1159         else: return "", ""
1160
1161 def on_pulse():
1162         """The things which should happen on each pulse, aside from reloads."""
1163
1164         # open the listening socket if it hasn't been already
1165         if not hasattr(universe, "listening_socket"):
1166                 universe.initialize_server_socket()
1167
1168         # assign a user if a new connection is waiting
1169         user = check_for_connection(universe.listening_socket)
1170         if user: universe.userlist.append(user)
1171
1172         # iterate over the connected users
1173         for user in universe.userlist: user.pulse()
1174
1175         # add an element for counters if it doesn't exist
1176         if not "counters" in universe.categories["internal"]:
1177                 universe.categories["internal"]["counters"] = Element("internal:counters", universe)
1178
1179         # update the log every now and then
1180         if not universe.categories["internal"]["counters"].getint("mark"):
1181                 log(str(len(universe.userlist)) + " connection(s)")
1182                 universe.categories["internal"]["counters"].set("mark", universe.categories["internal"]["time"].getint("frequency_log"))
1183         else: universe.categories["internal"]["counters"].set("mark", universe.categories["internal"]["counters"].getint("mark") - 1)
1184
1185         # periodically save everything
1186         if not universe.categories["internal"]["counters"].getint("save"):
1187                 universe.save()
1188                 universe.categories["internal"]["counters"].set("save", universe.categories["internal"]["time"].getint("frequency_save"))
1189         else: universe.categories["internal"]["counters"].set("save", universe.categories["internal"]["counters"].getint("save") - 1)
1190
1191         # pause for a configurable amount of time (decimal seconds)
1192         sleep(universe.categories["internal"]["time"].getfloat("increment"))
1193
1194         # increase the elapsed increment counter
1195         universe.categories["internal"]["counters"].set("elapsed", universe.categories["internal"]["counters"].getint("elapsed") + 1)
1196
1197 def reload_data():
1198         """Reload all relevant objects."""
1199         for user in universe.userlist[:]: user.reload()
1200         for element in universe.contents.values():
1201                 if element.origin.is_writeable(): element.reload()
1202         universe.load()
1203
1204 def check_for_connection(listening_socket):
1205         """Check for a waiting connection and return a new user object."""
1206
1207         # try to accept a new connection
1208         try:
1209                 connection, address = listening_socket.accept()
1210         except:
1211                 return None
1212
1213         # note that we got one
1214         log("Connection from " + address[0], 2)
1215
1216         # disable blocking so we can proceed whether or not we can send/receive
1217         connection.setblocking(0)
1218
1219         # create a new user object
1220         user = User()
1221
1222         # associate this connection with it
1223         user.connection = connection
1224
1225         # set the user's ipa from the connection's ipa
1226         user.address = address[0]
1227
1228         # let the client know we WILL EOR
1229         user.send(IAC+WILL+EOR, raw=True)
1230         user.negotiation_pause = 2
1231
1232         # return the new user object
1233         return user
1234
1235 def get_menu(state, error=None, echoing=True, terminator="", choices=None):
1236         """Show the correct menu text to a user."""
1237
1238         # make sure we don't reuse a mutable sequence by default
1239         if choices is None: choices = {}
1240
1241         # begin with a telnet echo command sequence if needed
1242         message = get_echo_sequence(state, echoing)
1243
1244         # get the description or error text
1245         message += get_menu_description(state, error)
1246
1247         # get menu choices for the current state
1248         message += get_formatted_menu_choices(state, choices)
1249
1250         # try to get a prompt, if it was defined
1251         message += get_menu_prompt(state)
1252
1253         # throw in the default choice, if it exists
1254         message += get_formatted_default_menu_choice(state)
1255
1256         # display a message indicating if echo is off
1257         message += get_echo_message(state)
1258
1259         # tack on EOR or GA to indicate the prompt will not be followed by CRLF
1260         message += terminator
1261
1262         # return the assembly of various strings defined above
1263         return message
1264
1265 def menu_echo_on(state):
1266         """True if echo is on, false if it is off."""
1267         return universe.categories["menu"][state].getboolean("echo", True)
1268
1269 def get_echo_sequence(state, echoing):
1270         """Build the appropriate IAC WILL/WONT ECHO sequence as needed."""
1271
1272         # if the user has echo on and the menu specifies it should be turned
1273         # off, send: iac + will + echo + null
1274         if echoing and not menu_echo_on(state): return IAC+WILL+ECHO
1275
1276         # if echo is not set to off in the menu and the user curently has echo
1277         # off, send: iac + wont + echo + null
1278         elif not echoing and menu_echo_on(state): return IAC+WONT+ECHO
1279
1280         # default is not to send an echo control sequence at all
1281         else: return ""
1282
1283 def get_echo_message(state):
1284         """Return a message indicating that echo is off."""
1285         if menu_echo_on(state): return ""
1286         else: return "(won't echo) "
1287
1288 def get_default_menu_choice(state):
1289         """Return the default choice for a menu."""
1290         return universe.categories["menu"][state].get("default")
1291
1292 def get_formatted_default_menu_choice(state):
1293         """Default menu choice foratted for inclusion in a prompt string."""
1294         default_choice = get_default_menu_choice(state)
1295         if default_choice: return "[$(red)" + default_choice + "$(nrm)] "
1296         else: return ""
1297
1298 def get_menu_description(state, error):
1299         """Get the description or error text."""
1300
1301         # an error condition was raised by the handler
1302         if error:
1303
1304                 # try to get an error message matching the condition
1305                 # and current state
1306                 description = universe.categories["menu"][state].get("error_" + error)
1307                 if not description: description = "That is not a valid choice..."
1308                 description = "$(red)" + description + "$(nrm)"
1309
1310         # there was no error condition
1311         else:
1312
1313                 # try to get a menu description for the current state
1314                 description = universe.categories["menu"][state].get("description")
1315
1316         # return the description or error message
1317         if description: description += "$(eol)$(eol)"
1318         return description
1319
1320 def get_menu_prompt(state):
1321         """Try to get a prompt, if it was defined."""
1322         prompt = universe.categories["menu"][state].get("prompt")
1323         if prompt: prompt += " "
1324         return prompt
1325
1326 def get_menu_choices(user):
1327         """Return a dict of choice:meaning."""
1328         menu = universe.categories["menu"][user.state]
1329         create_choices = menu.get("create")
1330         if create_choices: choices = eval(create_choices)
1331         else: choices = {}
1332         ignores = []
1333         options = {}
1334         creates = {}
1335         for facet in menu.facets():
1336                 if facet.startswith("demand_") and not eval(universe.categories["menu"][user.state].get(facet)):
1337                         ignores.append(facet.split("_", 2)[1])
1338                 elif facet.startswith("create_"):
1339                         creates[facet] = facet.split("_", 2)[1]
1340                 elif facet.startswith("choice_"):
1341                         options[facet] = facet.split("_", 2)[1]
1342         for facet in creates.keys():
1343                 if not creates[facet] in ignores:
1344                         choices[creates[facet]] = eval(menu.get(facet))
1345         for facet in options.keys():
1346                 if not options[facet] in ignores:
1347                         choices[options[facet]] = menu.get(facet)
1348         return choices
1349
1350 def get_formatted_menu_choices(state, choices):
1351         """Returns a formatted string of menu choices."""
1352         choice_output = ""
1353         choice_keys = choices.keys()
1354         choice_keys.sort()
1355         for choice in choice_keys:
1356                 choice_output += "   [$(red)" + choice + "$(nrm)]  " + choices[choice] + "$(eol)"
1357         if choice_output: choice_output += "$(eol)"
1358         return choice_output
1359
1360 def get_menu_branches(state):
1361         """Return a dict of choice:branch."""
1362         branches = {}
1363         for facet in universe.categories["menu"][state].facets():
1364                 if facet.startswith("branch_"):
1365                         branches[facet.split("_", 2)[1]] = universe.categories["menu"][state].get(facet)
1366         return branches
1367
1368 def get_default_branch(state):
1369         """Return the default branch."""
1370         return universe.categories["menu"][state].get("branch")
1371
1372 def get_choice_branch(user, choice):
1373         """Returns the new state matching the given choice."""
1374         branches = get_menu_branches(user.state)
1375         if choice in branches.keys(): return branches[choice]
1376         elif choice in user.menu_choices.keys(): return get_default_branch(user.state)
1377         else: return ""
1378
1379 def get_menu_actions(state):
1380         """Return a dict of choice:branch."""
1381         actions = {}
1382         for facet in universe.categories["menu"][state].facets():
1383                 if facet.startswith("action_"):
1384                         actions[facet.split("_", 2)[1]] = universe.categories["menu"][state].get(facet)
1385         return actions
1386
1387 def get_default_action(state):
1388         """Return the default action."""
1389         return universe.categories["menu"][state].get("action")
1390
1391 def get_choice_action(user, choice):
1392         """Run any indicated script for the given choice."""
1393         actions = get_menu_actions(user.state)
1394         if choice in actions.keys(): return actions[choice]
1395         elif choice in user.menu_choices.keys(): return get_default_action(user.state)
1396         else: return ""
1397
1398 def handle_user_input(user):
1399         """The main handler, branches to a state-specific handler."""
1400
1401         # if the user's client echo is off, send a blank line for aesthetics
1402         if user.echoing: user.received_newline = True
1403
1404         # check to make sure the state is expected, then call that handler
1405         if "handler_" + user.state in globals():
1406                 exec("handler_" + user.state + "(user)")
1407         else:
1408                 generic_menu_handler(user)
1409
1410         # since we got input, flag that the menu/prompt needs to be redisplayed
1411         user.menu_seen = False
1412
1413 def generic_menu_handler(user):
1414         """A generic menu choice handler."""
1415
1416         # get a lower-case representation of the next line of input
1417         if user.input_queue:
1418                 choice = user.input_queue.pop(0)
1419                 if choice: choice = choice.lower()
1420         else: choice = ""
1421         if not choice: choice = get_default_menu_choice(user.state)
1422         if choice in user.menu_choices:
1423                 exec(get_choice_action(user, choice))
1424                 new_state = get_choice_branch(user, choice)
1425                 if new_state: user.state = new_state
1426         else: user.error = "default"
1427
1428 def handler_entering_account_name(user):
1429         """Handle the login account name."""
1430
1431         # get the next waiting line of input
1432         input_data = user.input_queue.pop(0)
1433
1434         # did the user enter anything?
1435         if input_data:
1436                 
1437                 # keep only the first word and convert to lower-case
1438                 name = input_data.lower()
1439
1440                 # fail if there are non-alphanumeric characters
1441                 if name != filter(lambda x: x>="0" and x<="9" or x>="a" and x<="z", name):
1442                         user.error = "bad_name"
1443
1444                 # if that account exists, time to request a password
1445                 elif name in universe.categories["account"]:
1446                         user.account = universe.categories["account"][name]
1447                         user.state = "checking_password"
1448
1449                 # otherwise, this could be a brand new user
1450                 else:
1451                         user.account = Element("account:" + name, universe)
1452                         user.account.set("name", name)
1453                         log("New user: " + name, 2)
1454                         user.state = "checking_new_account_name"
1455
1456         # if the user entered nothing for a name, then buhbye
1457         else:
1458                 user.state = "disconnecting"
1459
1460 def handler_checking_password(user):
1461         """Handle the login account password."""
1462
1463         # get the next waiting line of input
1464         input_data = user.input_queue.pop(0)
1465
1466         # does the hashed input equal the stored hash?
1467         if new_md5(user.account.get("name") + input_data).hexdigest() == user.account.get("passhash"):
1468
1469                 # if so, set the username and load from cold storage
1470                 if not user.replace_old_connections():
1471                         user.authenticate()
1472                         user.state = "main_utility"
1473
1474         # if at first your hashes don't match, try, try again
1475         elif user.password_tries < universe.categories["internal"]["limits"].getint("password_tries") - 1:
1476                 user.password_tries += 1
1477                 user.error = "incorrect"
1478
1479         # we've exceeded the maximum number of password failures, so disconnect
1480         else:
1481                 user.send("$(eol)$(red)Too many failed password attempts...$(nrm)$(eol)")
1482                 user.state = "disconnecting"
1483
1484 def handler_entering_new_password(user):
1485         """Handle a new password entry."""
1486
1487         # get the next waiting line of input
1488         input_data = user.input_queue.pop(0)
1489
1490         # make sure the password is strong--at least one upper, one lower and
1491         # one digit, seven or more characters in length
1492         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)):
1493
1494                 # hash and store it, then move on to verification
1495                 user.account.set("passhash",  new_md5(user.account.get("name") + input_data).hexdigest())
1496                 user.state = "verifying_new_password"
1497
1498         # the password was weak, try again if you haven't tried too many times
1499         elif user.password_tries < universe.categories["internal"]["limits"].getint("password_tries") - 1:
1500                 user.password_tries += 1
1501                 user.error = "weak"
1502
1503         # too many tries, so adios
1504         else:
1505                 user.send("$(eol)$(red)Too many failed password attempts...$(nrm)$(eol)")
1506                 user.account.destroy()
1507                 user.state = "disconnecting"
1508
1509 def handler_verifying_new_password(user):
1510         """Handle the re-entered new password for verification."""
1511
1512         # get the next waiting line of input
1513         input_data = user.input_queue.pop(0)
1514
1515         # hash the input and match it to storage
1516         if new_md5(user.account.get("name") + input_data).hexdigest() == user.account.get("passhash"):
1517                 user.authenticate()
1518
1519                 # the hashes matched, so go active
1520                 if not user.replace_old_connections(): user.state = "main_utility"
1521
1522         # go back to entering the new password as long as you haven't tried
1523         # too many times
1524         elif user.password_tries < universe.categories["internal"]["limits"].getint("password_tries") - 1:
1525                 user.password_tries += 1
1526                 user.error = "differs"
1527                 user.state = "entering_new_password"
1528
1529         # otherwise, sayonara
1530         else:
1531                 user.send("$(eol)$(red)Too many failed password attempts...$(nrm)$(eol)")
1532                 user.account.destroy()
1533                 user.state = "disconnecting"
1534
1535 def handler_active(user):
1536         """Handle input for active users."""
1537
1538         # get the next waiting line of input
1539         input_data = user.input_queue.pop(0)
1540
1541         # is there input?
1542         if input_data:
1543
1544                 # split out the command and parameters
1545                 actor = user.avatar
1546                 mode = actor.get("mode")
1547                 if mode and input_data.startswith("!"):
1548                         command_name, parameters = first_word(input_data[1:])
1549                 elif mode == "chat":
1550                         command_name = "say"
1551                         parameters = input_data
1552                 else:
1553                         command_name, parameters = first_word(input_data)
1554
1555                 # lowercase the command
1556                 command_name = command_name.lower()
1557
1558                 # the command matches a command word for which we have data
1559                 if command_name in universe.categories["command"]:
1560                         command = universe.categories["command"][command_name]
1561                 else: command = None
1562
1563                 # if it's allowed, do it
1564                 if actor.can_run(command): exec(command.get("action"))
1565
1566                 # otherwise, give an error
1567                 elif command_name: command_error(actor, input_data)
1568
1569         # if no input, just idle back with a prompt
1570         else: user.send("", just_prompt=True)
1571         
1572 def command_halt(actor, parameters):
1573         """Halt the world."""
1574         if actor.owner:
1575
1576                 # see if there's a message or use a generic one
1577                 if parameters: message = "Halting: " + parameters
1578                 else: message = "User " + actor.owner.account.get("name") + " halted the world."
1579
1580                 # let everyone know
1581                 broadcast(message, add_prompt=False)
1582                 log(message, 8)
1583
1584                 # set a flag to terminate the world
1585                 universe.terminate_flag = True
1586
1587 def command_reload(actor):
1588         """Reload all code modules, configs and data."""
1589         if actor.owner:
1590
1591                 # let the user know and log
1592                 actor.send("Reloading all code modules, configs and data.")
1593                 log("User " + actor.owner.account.get("name") + " reloaded the world.", 8)
1594
1595                 # set a flag to reload
1596                 universe.reload_flag = True
1597
1598 def command_quit(actor):
1599         """Leave the world and go back to the main menu."""
1600         if actor.owner:
1601                 actor.owner.state = "main_utility"
1602                 actor.owner.deactivate_avatar()
1603
1604 def command_help(actor, parameters):
1605         """List available commands and provide help for commands."""
1606
1607         # did the user ask for help on a specific command word?
1608         if parameters and actor.owner:
1609
1610                 # is the command word one for which we have data?
1611                 if parameters in universe.categories["command"]:
1612                         command = universe.categories["command"][parameters]
1613                 else: command = None
1614
1615                 # only for allowed commands
1616                 if actor.can_run(command):
1617
1618                         # add a description if provided
1619                         description = command.get("description")
1620                         if not description:
1621                                 description = "(no short description provided)"
1622                         if command.getboolean("administrative"): output = "$(red)"
1623                         else: output = "$(grn)"
1624                         output += parameters + "$(nrm) - " + description + "$(eol)$(eol)"
1625
1626                         # add the help text if provided
1627                         help_text = command.get("help")
1628                         if not help_text:
1629                                 help_text = "No help is provided for this command."
1630                         output += help_text
1631
1632                         # list related commands
1633                         see_also = command.getlist("see_also")
1634                         if see_also:
1635                                 really_see_also = ""
1636                                 for item in see_also:
1637                                         if item in universe.categories["command"]:
1638                                                 command = universe.categories["command"][item]
1639                                                 if actor.can_run(command):
1640                                                         if really_see_also:
1641                                                                 really_see_also += ", "
1642                                                         if command.getboolean("administrative"):
1643                                                                 really_see_also += "$(red)"
1644                                                         else:
1645                                                                 really_see_also += "$(grn)"
1646                                                         really_see_also += item + "$(nrm)"
1647                                 if really_see_also:
1648                                         output += "$(eol)$(eol)See also: " + really_see_also
1649
1650                 # no data for the requested command word
1651                 else:
1652                         output = "That is not an available command."
1653
1654         # no specific command word was indicated
1655         else:
1656
1657                 # give a sorted list of commands with descriptions if provided
1658                 output = "These are the commands available to you:$(eol)$(eol)"
1659                 sorted_commands = universe.categories["command"].keys()
1660                 sorted_commands.sort()
1661                 for item in sorted_commands:
1662                         command = universe.categories["command"][item]
1663                         if actor.can_run(command):
1664                                 description = command.get("description")
1665                                 if not description:
1666                                         description = "(no short description provided)"
1667                                 if command.getboolean("administrative"): output += "   $(red)"
1668                                 else: output += "   $(grn)"
1669                                 output += item + "$(nrm) - " + description + "$(eol)"
1670                 output += "$(eol)Enter \"help COMMAND\" for help on a command named \"COMMAND\"."
1671
1672         # send the accumulated output to the user
1673         actor.send(output)
1674
1675 def command_move(actor, parameters):
1676         """Move the avatar in a given direction."""
1677         if parameters in universe.contents[actor.get("location")].portals():
1678                 actor.move_direction(parameters)
1679         else: actor.send("You cannot go that way.")
1680
1681 def command_look(actor, parameters):
1682         """Look around."""
1683         if parameters: actor.send("You can't look at or in anything yet.")
1684         else: actor.look_at(actor.get("location"))
1685
1686 def command_say(actor, parameters):
1687         """Speak to others in the same room."""
1688
1689         # check for replacement macros
1690         if replace_macros(actor.owner, parameters, True) != parameters:
1691                 actor.send("You cannot speak $_(replacement macros).")
1692
1693         # the user entered a message
1694         elif parameters:
1695
1696                 # get rid of quote marks on the ends of the message
1697                 message = parameters.strip("\"'`")
1698
1699                 # match the punctuation used, if any, to an action
1700                 actions = universe.categories["internal"]["language"].getdict("actions")
1701                 default_punctuation = universe.categories["internal"]["language"].get("default_punctuation")
1702                 action = ""
1703                 for mark in actions.keys():
1704                         if message.endswith(mark):
1705                                 action = actions[mark]
1706                                 break
1707
1708                 # add punctuation if needed
1709                 if not action:
1710                         action = actions[default_punctuation]
1711                         if message and not message[-1] in punctuation:
1712                                 message += default_punctuation
1713
1714                 # decapitalize the first letter to improve matching
1715                 if message and message[0] in uppercase:
1716                         message = message[0].lower() + message[1:]
1717
1718                 # iterate over all words in message, replacing typos
1719                 typos = universe.categories["internal"]["language"].getdict("typos")
1720                 words = message.split()
1721                 for index in range(len(words)):
1722                         word = words[index]
1723                         bare_word = word.strip(punctuation)
1724                         if bare_word in typos.keys():
1725                                 words[index] = word.replace(bare_word, typos[bare_word])
1726                 message = " ".join(words)
1727
1728                 # capitalize the first letter
1729                 message = message[0].upper() + message[1:]
1730
1731                 # tell the room
1732                 actor.echo_to_location(actor.get("name") + " " + action + "s, \"" + message + "\"")
1733                 actor.send("You " + action + ", \"" + message + "\"")
1734
1735         # there was no message
1736         else:
1737                 actor.send("What do you want to say?")
1738
1739 def command_chat(actor):
1740         """Toggle chat mode."""
1741         mode = actor.get("mode")
1742         if not mode:
1743                 actor.set("mode", "chat")
1744                 actor.send("Entering chat mode (use $(grn)!chat$(nrm) to exit).")
1745         elif mode == "chat":
1746                 actor.remove_facet("mode")
1747                 actor.send("Exiting chat mode.")
1748         else: actor.send("Sorry, but you're already busy with something else!")
1749
1750 def command_show(actor, parameters):
1751         """Show program data."""
1752         message = ""
1753         arguments = parameters.split()
1754         if not parameters: message = "What do you want to show?"
1755         elif arguments[0] == "time":
1756                 message = universe.categories["internal"]["counters"].get("elapsed") + " increments elapsed since the world was created."
1757         elif arguments[0] == "categories":
1758                 message = "These are the element categories:$(eol)"
1759                 categories = universe.categories.keys()
1760                 categories.sort()
1761                 for category in categories: message += "$(eol)   $(grn)" + category + "$(nrm)"
1762         elif arguments[0] == "files":
1763                 message = "These are the current files containing the universe:$(eol)"
1764                 filenames = universe.files.keys()
1765                 filenames.sort()
1766                 for filename in filenames:
1767                         if universe.files[filename].is_writeable(): status = "rw"
1768                         else: status = "ro"
1769                         message += "$(eol)   $(red)(" + status + ") $(grn)" + filename + "$(nrm)"
1770         elif arguments[0] == "category":
1771                 if len(arguments) != 2: message = "You must specify one category."
1772                 elif arguments[1] in universe.categories:
1773                         message = "These are the elements in the \"" + arguments[1] + "\" category:$(eol)"
1774                         elements = [(universe.categories[arguments[1]][x].key) for x in universe.categories[arguments[1]].keys()]
1775                         elements.sort()
1776                         for element in elements:
1777                                 message += "$(eol)   $(grn)" + element + "$(nrm)"
1778                 else: message = "Category \"" + arguments[1] + "\" does not exist."
1779         elif arguments[0] == "file":
1780                 if len(arguments) != 2: message = "You must specify one file."
1781                 elif arguments[1] in universe.files:
1782                         message = "These are the elements in the \"" + arguments[1] + "\" file:$(eol)"
1783                         elements = universe.files[arguments[1]].data.sections()
1784                         elements.sort()
1785                         for element in elements:
1786                                 message += "$(eol)   $(grn)" + element + "$(nrm)"
1787                 else: message = "Category \"" + arguments[1] + "\" does not exist."
1788         elif arguments[0] == "element":
1789                 if len(arguments) != 2: message = "You must specify one element."
1790                 elif arguments[1] in universe.contents:
1791                         element = universe.contents[arguments[1]]
1792                         message = "These are the properties of the \"" + arguments[1] + "\" element (in \"" + element.origin.filename + "\"):$(eol)"
1793                         facets = element.facets()
1794                         facets.sort()
1795                         for facet in facets:
1796                                 message += "$(eol)   $(grn)" + facet + ": $(red)" + escape_macros(element.get(facet)) + "$(nrm)"
1797                 else: message = "Element \"" + arguments[1] + "\" does not exist."
1798         elif arguments[0] == "result":
1799                 if len(arguments) < 2: message = "You need to specify an expression."
1800                 else:
1801                         try:
1802                                 message = repr(eval(" ".join(arguments[1:])))
1803                         except:
1804                                 message = "Your expression raised an exception!"
1805         elif arguments[0] == "log":
1806                 if len(arguments) == 4:
1807                         if match("^\d+$", arguments[3]) and int(arguments[3]) >= 0:
1808                                 stop = int(arguments[3])
1809                         else: stop = -1
1810                 else: stop = 0
1811                 if len(arguments) >= 3:
1812                         if match("^\d+$", arguments[2]) and int(arguments[2]) > 0:
1813                                 start = int(arguments[2])
1814                         else: start = -1
1815                 else: start = 10
1816                 if len(arguments) >= 2:
1817                         if match("^\d+$", arguments[1]) and 0 <= int(arguments[1]) <= 9:
1818                                 level = int(arguments[1])
1819                         else: level = -1
1820                 elif 0 <= actor.owner.account.getint("loglevel") <= 9:
1821                         level = actor.owner.account.getint("loglevel")
1822                 else: level = 1
1823                 if level > -1 and start > -1 and stop > -1:
1824                         message = get_loglines(level, start, stop)
1825                 else: message = "When specified, level must be 0-9 (default 1), start and stop must be >=1 (default 10 and 1)."
1826         else: message = "I don't know what \"" + parameters + "\" is."
1827         actor.send(message)
1828
1829 def command_create(actor, parameters):
1830         """Create an element if it does not exist."""
1831         if not parameters: message = "You must at least specify an element to create."
1832         elif not actor.owner: message = ""
1833         else:
1834                 arguments = parameters.split()
1835                 if len(arguments) == 1: arguments.append("")
1836                 if len(arguments) == 2:
1837                         element, filename = arguments
1838                         if element in universe.contents: message = "The \"" + element + "\" element already exists."
1839                         else:
1840                                 message = "You create \"" + element + "\" within the universe."
1841                                 logline = actor.owner.account.get("name") + " created an element: " + element
1842                                 if filename:
1843                                         logline += " in file " + filename
1844                                         if filename not in universe.files:
1845                                                 message += " Warning: \"" + filename + "\" is not yet included in any other file and will not be read on startup unless this is remedied."
1846                                 Element(element, universe, filename)
1847                                 log(logline, 6)
1848                 elif len(arguments) > 2: message = "You can only specify an element and a filename."
1849         actor.send(message)
1850
1851 def command_destroy(actor, parameters):
1852         """Destroy an element if it exists."""
1853         if actor.owner:
1854                 if not parameters: message = "You must specify an element to destroy."
1855                 else:
1856                         if parameters not in universe.contents: message = "The \"" + parameters + "\" element does not exist."
1857                         else:
1858                                 universe.contents[parameters].destroy()
1859                                 message = "You destroy \"" + parameters + "\" within the universe."
1860                                 log(actor.owner.account.get("name") + " destroyed an element: " + parameters, 6)
1861                 actor.send(message)
1862
1863 def command_set(actor, parameters):
1864         """Set a facet of an element."""
1865         if not parameters: message = "You must specify an element, a facet and a value."
1866         else:
1867                 arguments = parameters.split(" ", 2)
1868                 if len(arguments) == 1: message = "What facet of element \"" + arguments[0] + "\" would you like to set?"
1869                 elif len(arguments) == 2: message = "What value would you like to set for the \"" + arguments[1] + "\" facet of the \"" + arguments[0] + "\" element?"
1870                 else:
1871                         element, facet, value = arguments
1872                         if element not in universe.contents: message = "The \"" + element + "\" element does not exist."
1873                         else:
1874                                 universe.contents[element].set(facet, value)
1875                                 message = "You have successfully (re)set the \"" + facet + "\" facet of element \"" + element + "\". Try \"show element " + element + "\" for verification."
1876         actor.send(message)
1877
1878 def command_delete(actor, parameters):
1879         """Delete a facet from an element."""
1880         if not parameters: message = "You must specify an element and a facet."
1881         else:
1882                 arguments = parameters.split(" ")
1883                 if len(arguments) == 1: message = "What facet of element \"" + arguments[0] + "\" would you like to delete?"
1884                 elif len(arguments) != 2: message = "You may only specify an element and a facet."
1885                 else:
1886                         element, facet = arguments
1887                         if element not in universe.contents: message = "The \"" + element + "\" element does not exist."
1888                         elif facet not in universe.contents[element].facets(): message = "The \"" + element + "\" element has no \"" + facet + "\" facet."
1889                         else:
1890                                 universe.contents[element].remove_facet(facet)
1891                                 message = "You have successfully deleted the \"" + facet + "\" facet of element \"" + element + "\". Try \"show element " + element + "\" for verification."
1892         actor.send(message)
1893
1894 def command_error(actor, input_data):
1895         """Generic error for an unrecognized command word."""
1896
1897         # 90% of the time use a generic error
1898         if randrange(10):
1899                 message = "I'm not sure what \"" + input_data + "\" means..."
1900
1901         # 10% of the time use the classic diku error
1902         else:
1903                 message = "Arglebargle, glop-glyf!?!"
1904
1905         # send the error message
1906         actor.send(message)
1907
1908 def daemonize():
1909         """Fork and disassociate from everything."""
1910         if universe.contents["internal:process"].getboolean("daemon"):
1911                 import sys
1912                 from resource import getrlimit, RLIMIT_NOFILE
1913                 log("Disassociating from the controlling terminal.")
1914                 if fork(): _exit(0)
1915                 setsid()
1916                 if fork(): _exit(0)
1917                 chdir("/")
1918                 umask(0)
1919                 for stdpipe in range(3): close(stdpipe)
1920                 sys.stdin = sys.__stdin__ = file("/dev/null", "r")
1921                 sys.stdout = sys.stderr = sys.__stdout__ = sys.__stderr__ = file("/dev/null", "w")
1922
1923 def create_pidfile(universe):
1924         """Write a file containing the current process ID."""
1925         pid = str(getpid())
1926         log("Process ID: " + pid)
1927         file_name = universe.contents["internal:process"].get("pidfile")
1928         if file_name:
1929                 if not isabs(file_name):
1930                         file_name = path_join(universe.startdir, file_name)
1931                 file_descriptor = file(file_name, 'w')
1932                 file_descriptor.write(pid + "\n")
1933                 file_descriptor.flush()
1934                 file_descriptor.close()
1935
1936 def remove_pidfile(universe):
1937         """Remove the file containing the current process ID."""
1938         file_name = universe.contents["internal:process"].get("pidfile")
1939         if file_name:
1940                 if not isabs(file_name):
1941                         file_name = path_join(universe.startdir, file_name)
1942                 if access(file_name, W_OK): remove(file_name)
1943
1944 def excepthook(excepttype, value, traceback):
1945         """Handle uncaught exceptions."""
1946
1947         # assemble the list of errors into a single string
1948         message = "".join(format_exception(excepttype, value, traceback))
1949
1950         # try to log it, if possible
1951         try: log(message, 9)
1952         except: pass
1953
1954         # try to write it to stderr, if possible
1955         try: stderr.write(message)
1956         except: pass
1957
1958 def sighook(what, where):
1959         """Handle external signals."""
1960
1961         # a generic message
1962         message = "Caught signal: "
1963
1964         # for a hangup signal
1965         if what == SIGHUP:
1966                 message += "hangup (reloading)"
1967                 universe.reload_flag = True
1968
1969         # for a terminate signal
1970         elif what == SIGTERM:
1971                 message += "terminate (halting)"
1972                 universe.terminate_flag = True
1973
1974         # catchall for unexpected signals
1975         else: message += str(what) + " (unhandled)"
1976
1977         # log what happened
1978         log(message, 8)
1979
1980 # redefine sys.excepthook with ours
1981 import sys
1982 sys.excepthook = excepthook
1983
1984 # assign the sgnal handlers
1985 signal(SIGHUP, sighook)
1986 signal(SIGTERM, sighook)
1987
1988 # if there is no universe, create an empty one
1989 if not "universe" in locals():
1990         if len(argv) > 1: conffile = argv[1]
1991         else: conffile = ""
1992         universe = Universe(conffile, True)
1993 elif universe.reload_flag:
1994         universe = universe.new()
1995         reload_data()
1996