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