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