Proper RFC 1143 Telnet option negotiation queue.
[mudpy.git] / lib / mudpy / misc.py
index 3464744..3b11a12 100644 (file)
@@ -185,11 +185,22 @@ class Element:
       raw=False,
       flush=False,
       add_prompt=True,
-      just_prompt=False
+      just_prompt=False,
+      add_terminator=False,
+      prepend_padding=True
    ):
       u"""Convenience method to pass messages to an owner."""
       if self.owner:
-         self.owner.send(message, eol, raw, flush, add_prompt, just_prompt)
+         self.owner.send(
+            message,
+            eol,
+            raw,
+            flush,
+            add_prompt,
+            just_prompt,
+            add_terminator,
+            prepend_padding
+         )
 
    def can_run(self, command):
       u"""Check if the user can run this command object."""
@@ -642,15 +653,13 @@ class User:
 
    def __init__(self):
       u"""Default values for the in-memory user variables."""
+      import telnet
       self.account = None
       self.address = u""
       self.authenticated = False
       self.avatar = None
-      self.client_displays_binary = False
-      self.client_sends_binary = False
       self.columns = 79
       self.connection = None
-      self.echoing = True
       self.error = u""
       self.input_queue = []
       self.last_address = u""
@@ -661,9 +670,8 @@ class User:
       self.output_queue = []
       self.partial_input = ""
       self.password_tries = 0
-      self.received_newline = True
       self.state = u"initial"
-      self.terminator = telnet_proto([u"IAC",u"GA"])
+      self.telopts = {}
 
    def quit(self):
       u"""Log, close the connection and remove."""
@@ -776,14 +784,6 @@ class User:
             old_user.connection = self.connection
             old_user.last_address = old_user.address
             old_user.address = self.address
-            old_user.client_displays_binary = self.client_displays_binary
-            old_user.client_sends_binary = self.client_sends_binary
-
-            # may need to tell the new connection to echo
-            if old_user.echoing:
-               old_user.send(
-                  get_echo_sequence(old_user.state, self.echoing), raw=True
-               )
 
             # take this one out of the list and delete
             self.remove()
@@ -823,8 +823,12 @@ class User:
 
    def adjust_echoing(self):
       u"""Adjust echoing to match state menu requirements."""
-      if self.echoing and not menu_echo_on(self.state): self.echoing = False
-      elif not self.echoing and menu_echo_on(self.state): self.echoing = True
+      import telnet
+      if telnet.is_enabled(self, telnet.TELOPT_ECHO, telnet.US):
+         if menu_echo_on(self.state):
+            telnet.disable(self, telnet.TELOPT_ECHO, telnet.US)
+      elif not menu_echo_on(self.state):
+         telnet.enable(self, telnet.TELOPT_ECHO, telnet.US)
 
    def remove(self):
       u"""Remove a user from the list of connected users."""
@@ -838,9 +842,11 @@ class User:
       flush=False,
       add_prompt=True,
       just_prompt=False,
-      add_terminator=False
+      add_terminator=False,
+      prepend_padding=True
    ):
       u"""Send arbitrary text to a connected user."""
+      import telnet
 
       # unless raw mode is on, clean it up all nice and pretty
       if not raw:
@@ -856,11 +862,10 @@ class User:
          # start with a newline, append the message, then end
          # with the optional eol string passed to this function
          # and the ansi escape to return to normal text
-         if not just_prompt:
-            if not self.output_queue or not self.output_queue[-1].endswith(
-               "\r\n"
-            ):
-               output = u"$(eol)$(eol)" + output
+         if not just_prompt and prepend_padding:
+            if not self.output_queue \
+               or not self.output_queue[-1].endswith("\r\n"):
+               output = u"$(eol)" + output
             elif not self.output_queue[-1].endswith(
                "\r\n\x1b[0m\r\n"
             ) and not self.output_queue[-1].endswith(
@@ -887,18 +892,18 @@ class User:
             output = wrap_ansi_text(output, wrap)
 
          # if supported by the client, encode it utf-8
-         if self.client_displays_binary:
+         if telnet.is_enabled(self, telnet.TELOPT_BINARY, telnet.US):
             encoded_output = output.encode(u"utf-8")
 
          # otherwise just send ascii
-         else:
-            encoded_output = output.encode(u"ascii", u"replace")
-
-         # inject appropriate echoing changes
-         encoded_output += get_echo_sequence(self.state, self.echoing)
+         else: encoded_output = output.encode(u"ascii", u"replace")
 
          # end with a terminator if requested
-         if add_terminator: encoded_output += self.terminator
+         if add_prompt or add_terminator:
+            if telnet.is_enabled(self, telnet.TELOPT_EOR, telnet.US):
+               encoded_output += telnet.telnet_proto(telnet.IAC, telnet.EOR)
+            elif not telnet.is_enabled(self, telnet.TELOPT_SGA, telnet.US):
+               encoded_output += telnet.telnet_proto(telnet.IAC, telnet.GA)
 
          # and tack it onto the queue
          self.output_queue.append(encoded_output)
@@ -946,10 +951,6 @@ class User:
    def flush(self):
       u"""Try to send the last item in the queue and remove it."""
       if self.output_queue:
-         if self.received_newline:
-            self.received_newline = False
-            if self.output_queue[0].startswith("\r\n"):
-               self.output_queue[0] = self.output_queue[0][2:]
          try:
             self.connection.send(self.output_queue[0])
             del self.output_queue[0]
@@ -966,7 +967,7 @@ class User:
 
    def enqueue_input(self):
       u"""Process and enqueue any new input."""
-      import unicodedata
+      import telnet, unicodedata
 
       # check for some input
       try:
@@ -981,7 +982,7 @@ class User:
          self.partial_input += raw_input
 
          # reply to and remove any IAC negotiation codes
-         self.negotiate_telnet_options()
+         telnet.negotiate_telnet_options(self)
 
          # separate multiple input lines
          new_input_lines = self.partial_input.split("\n")
@@ -1015,9 +1016,7 @@ class User:
                line = ""
 
             # log non-printable characters remaining
-            if not hasattr(
-               self, u"client_sends_binary"
-            ) or not self.client_sends_binary:
+            if telnet.is_enabled(self, telnet.TELOPT_BINARY, telnet.HIM):
                asciiline = filter(lambda x: " " <= x <= "~", line)
                if line != asciiline:
                   logline = u"Non-ASCII characters from "
@@ -1033,147 +1032,6 @@ class User:
                unicodedata.normalize( u"NFKC", unicode(line, u"utf-8") )
             )
 
-   def negotiate_telnet_options(self):
-      u"""Reply to/remove partial_input telnet negotiation options."""
-
-      # start at the begining of the input
-      position = 0
-
-      # make a local copy to play with
-      text = self.partial_input
-
-      # as long as we haven't checked it all
-      while position < len(text):
-
-         # jump to the first IAC you find
-         position = text.find(telnet_proto([u"IAC"]), position)
-
-         # if there wasn't an IAC in the input, we're done
-         if position < 0: break
-
-         # replace a double (literal) IAC if there's an LF later
-         elif len(text) > position+1 and text[position+1] == telnet_proto(
-            [u"IAC"]
-         ):
-            if text.find("\n", position) > 0:
-               text = text.replace(
-                  telnet_proto([u"IAC",u"IAC"]), telnet_proto([u"IAC"])
-               )
-            else: position += 1
-            position += 1
-
-         # implement an RFC 1143 option negotiation queue here
-         elif len(text) > position+2 and text[position+1] in (
-            telnet_proto([u"DO",u"DONT",u"WILL",u"WONT"])
-         ):
-            negotiation = text[position+1:position+3]
-
-            # if we turned echo off, ignore the confirmation
-            if not self.echoing and negotiation == telnet_proto(
-               [u"DO",u"TELOPT_ECHO"]
-            ):
-               self.send(
-                  telnet_proto([u"IAC",u"WILL",u"TELOPT_ECHO"]), raw=True
-               )
-
-            # BINARY mode handling for unicode support (RFC 856)
-            elif negotiation == telnet_proto([u"DO",u"TELOPT_BINARY"]):
-               self.send(
-                  telnet_proto([u"IAC",u"WILL",u"TELOPT_BINARY"]), raw=True
-               )
-               self.client_displays_binary = True
-            elif negotiation == telnet_proto([u"DONT",u"TELOPT_BINARY"]):
-               self.send(
-                  telnet_proto([u"IAC",u"WONT",u"TELOPT_BINARY"]), raw=True
-               )
-               self.client_displays_binary = False
-            elif negotiation == telnet_proto([u"WILL",u"TELOPT_BINARY"]):
-               self.send(
-                  telnet_proto([u"IAC",u"DO",u"TELOPT_BINARY"]), raw=True
-               )
-               self.client_sends_binary = True
-            elif negotiation == telnet_proto([u"WONT",u"TELOPT_BINARY"]):
-               self.send(
-                  telnet_proto([u"IAC",u"DONT",u"TELOPT_BINARY"]), raw=True
-               )
-               self.client_sends_binary = False
-
-            # allow LINEMODE (RFC 1184)
-            elif negotiation == telnet_proto([u"WILL",u"TELOPT_LINEMODE"]):
-               self.send(
-                  telnet_proto([u"IAC",u"DO",u"TELOPT_LINEMODE"]), raw=True
-               )
-            elif negotiation == telnet_proto([u"WONT",u"TELOPT_LINEMODE"]):
-               self.send(
-                  telnet_proto([u"IAC",u"DONT",u"TELOPT_LINEMODE"]), raw=True
-               )
-
-            # allow NAWS (RFC 1073)
-            elif negotiation == telnet_proto([u"WILL",u"TELOPT_NAWS"]):
-               self.send(
-                  telnet_proto([u"IAC",u"DO",u"TELOPT_NAWS"]), raw=True
-               )
-            elif negotiation == telnet_proto([u"WONT",u"TELOPT_NAWS"]):
-               self.send(
-                  telnet_proto([u"IAC",u"DONT",u"TELOPT_NAWS"]), raw=True
-               )
-
-            # if the client likes EOR (RFC 885) instead of GA, note it
-            elif negotiation == telnet_proto([u"DO",u"TELOPT_EOR"]):
-               self.send(
-                  telnet_proto([u"IAC",u"WILL",u"TELOPT_EOR"]), raw=True
-               )
-               self.terminator = telnet_proto([u"IAC",u"EOR"])
-            elif negotiation == telnet_proto([u"DONT",u"TELOPT_EOR"]):
-               self.send(
-                  telnet_proto([u"IAC",u"WONT",u"TELOPT_EOR"]), raw=True
-               )
-               if self.terminator == telnet_proto([u"IAC",u"EOR"]):
-                  self.terminator = telnet_proto([u"IAC",u"GA"])
-
-            # if the client doesn't want GA, oblige (RFC 858)
-            elif negotiation == telnet_proto([u"DO",u"TELOPT_SGA"]):
-               self.send(telnet_proto([u"IAC",u"WILL",u"TELOPT_SGA"]),
-                  raw=True)
-               if self.terminator == telnet_proto([u"IAC",u"GA"]):
-                  self.terminator = ""
-
-            # we don't want to allow anything else
-            elif text[position+1] == telnet_proto([u"DO"]):
-               self.send(
-                  telnet_proto([u"IAC",u"WONT"])+text[position+2], raw=True
-               )
-            elif text[position+1] == telnet_proto([u"WILL"]):
-               self.send(
-                  telnet_proto([u"IAC",u"DONT"])+text[position+2], raw=True
-               )
-
-            # strip the negotiation from the input
-            text = text.replace(text[position:position+3], "")
-
-         # subnegotiation options
-         elif len(text) > position+4 and text[
-            position:position+2
-         ] == telnet_proto([u"IAC",u"SB"]):
-            if text[position+2] == telnet_proto([u"TELOPT_NAWS"]):
-               self.columns = ord(text[position+3])*256+ord(text[position+4])
-            end_subnegotiation = text.find(
-               telnet_proto([u"IAC",u"SE"]), position
-            )
-            if end_subnegotiation > 0:
-               text = text[:position] + text[end_subnegotiation+2:]
-            else: position += 1
-
-         # otherwise, strip out a two-byte IAC command
-         elif len(text) > position+2:
-            text = text.replace(text[position:position+2], "")
-
-         # and this means we got the begining of an IAC
-         else: position += 1
-
-      # replace the input with our cleaned-up text
-      self.partial_input = text
-
    def new_avatar(self):
       u"""Instantiate a new, unconfigured avatar for this user."""
       counter = 0
@@ -1247,34 +1105,6 @@ def makedict(value):
    elif value.find(u":") > 0: return eval(u"{" + value + u"}")
    else: return { value: None }
 
-def telnet_proto(arguments):
-   u"""Return a concatenated series of Telnet protocol commands."""
-
-   # same names as bsd's arpa/telnet.h (telnetlib's are ambiguous)
-   telnet_commands = {
-      u"TELOPT_BINARY": 0, # RFC 856
-      u"TELOPT_ECHO": 1, # RFC 857
-      u"TELOPT_SGA": 3, # RFC 858
-      u"TELOPT_EOR": 25, # RFC 885
-      u"TELOPT_NAWS": 31, # RFC 1073
-      u"TELOPT_LINEMODE": 34, # RFC 1184
-      u"EOR": 239,
-      u"SE": 240,
-      u"GA": 249,
-      u"SB": 250,
-      u"WILL": 251,
-      u"WONT": 252,
-      u"DO": 253,
-      u"DONT": 254,
-      u"IAC": 255
-   }
-
-   # (this will need to be byte type during 2to3 migration)
-   command_series = ""
-   for argument in arguments:
-      command_series += chr(telnet_commands[argument])
-   return command_series
-
 def broadcast(message, add_prompt=True):
    u"""Send a message to all connected users."""
    for each_user in universe.userlist:
@@ -1699,6 +1529,7 @@ def reload_data():
 
 def check_for_connection(listening_socket):
    u"""Check for a waiting connection and return a new user object."""
+   import telnet
 
    # try to accept a new connection
    try:
@@ -1722,7 +1553,7 @@ def check_for_connection(listening_socket):
    user.address = address[0]
 
    # let the client know we WILL EOR (RFC 885)
-   user.send(telnet_proto([u"IAC",u"WILL",u"TELOPT_EOR"]), raw=True)
+   telnet.enable(user, telnet.TELOPT_EOR, telnet.US)
    user.negotiation_pause = 2
 
    # return the new user object
@@ -1756,22 +1587,6 @@ def menu_echo_on(state):
    u"""True if echo is on, false if it is off."""
    return universe.categories[u"menu"][state].getboolean(u"echo", True)
 
-def get_echo_sequence(state, echoing):
-   u"""Build the appropriate IAC WILL/WONT ECHO sequence as needed."""
-
-   # if the user has echo on and the menu specifies it should be turned
-   # off, send: iac + will + echo + null
-   if echoing and not menu_echo_on(state):
-      return telnet_proto([u"IAC",u"WILL",u"TELOPT_ECHO"])
-
-   # if echo is not set to off in the menu and the user curently has echo
-   # off, send: iac + wont + echo + null
-   elif not echoing and menu_echo_on(state):
-      return telnet_proto([u"IAC",u"WONT",u"TELOPT_ECHO"])
-
-   # default is not to send an echo control sequence at all
-   else: return ""
-
 def get_echo_message(state):
    u"""Return a message indicating that echo is off."""
    if menu_echo_on(state): return u""
@@ -1899,9 +1714,11 @@ def get_choice_action(user, choice):
 
 def handle_user_input(user):
    u"""The main handler, branches to a state-specific handler."""
+   import telnet
 
    # if the user's client echo is off, send a blank line for aesthetics
-   if user.echoing: user.received_newline = True
+   if telnet.is_enabled(user, telnet.TELOPT_ECHO, telnet.US):
+      user.send(u"", add_prompt=False, prepend_padding=False)
 
    # check to make sure the state is expected, then call that handler
    if u"handler_" + user.state in globals():