# -*- test-case-name: twisted.conch.test.test_telnet -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.

"""
Tests for L{twisted.conch.telnet}.
"""

from __future__ import absolute_import, division

from zope.interface import implementer
from zope.interface.verify import verifyObject

from twisted.internet import defer

from twisted.conch import telnet

from twisted.trial import unittest
from twisted.test import proto_helpers
from twisted.python.compat import iterbytes


@implementer(telnet.ITelnetProtocol)
class TestProtocol:
    localEnableable = ()
    remoteEnableable = ()

    def __init__(self):
        self.bytes = b''
        self.subcmd = []
        self.calls = []

        self.enabledLocal = []
        self.enabledRemote = []
        self.disabledLocal = []
        self.disabledRemote = []

    def makeConnection(self, transport):
        d = transport.negotiationMap = {}
        d[b'\x12'] = self.neg_TEST_COMMAND

        d = transport.commandMap = tr
ansport.commandMap.copy()
        for cmd in ('NOP', 'DM', 'BRK', 'IP', 'AO', 'AYT', 'EC', 'EL', 'GA'):
            d[getattr(telnet, cmd)] = lambda arg, cmd=cmd: self.calls.append(cmd)

    def dataReceived(self, bytes):
        self.bytes += bytes

    def connectionLost(self, reason):
        pass

    def neg_TEST_COMMAND(self, payload):
        self.subcmd = payload

    def enableLocal(sel
f, option):
        if option in self.localEnableable:
            self.enabledLocal.append(option)
            return True
        return False

    def disableLocal(self, option):
        self.disabledLocal.append(option)

    def enableRemote(self, option):
        if option in self.remoteEnableable:
            self.enabledRemote.append(option)
            return True
        return False

    def disableRemote(self, option):
        self.disabledRemote.append(option)



class InterfacesTests(unittest.TestCase):
    def test_interface(self):
        """
        L{telnet.TelnetProtocol} implements L{telnet.ITelnetProtocol}
        """
        p = telnet.TelnetProtocol()
        verifyObject(telnet.ITelnetProtocol, p)



class TelnetTransportTests(unittest.TestCase):
    """
    Tests for L{telnet.TelnetTransport}.
    """
    def setUp(self):
        self.p = telnet.TelnetTransport(TestProtocol)
        self.t = proto_helpers.StringTransport()
        self.p.makeConnection(self.t)

    def testRegularBytes(self):
        # Just send a bunch of bytes.  None of these do anything
        # with telnet.  They should pass right through to the
        # application layer.
        h = self.p.protocol

        L = [b"here are some bytes la la la",
             b"some more arrive here",
             b"lots of bytes to play with",
             b"la la la",
             b"ta de da",
             b"dum"]
        for b in L:
            self.p.dataReceived(b)

        self.assertEqual(h.bytes, b''.join(L))

    def testNewlineHandling(self):
        # Send various kinds of newlines and make sure they get translated
        # into \n.
        h = self.p.protocol

        L = [b"here is the first line\r\n",
             b"here is the second line\r\0",
             b"here is the third line\r\n",
             b"here is the last line\r\0"]

        for b in L:
            self.p.dataReceived(b)

        self.assertEqual(h.bytes, L[0][:-2] + b'\n' +
                          L[1][:-2] + b'\r' +
                          L[2][:-2] + b'\n' +
                          L[3][:-2] + b'\r')

    def testIACEscape(self):
        # Send a bunch of bytes and a couple quoted \xFFs.  Unquoted,
        # \xFF is a telnet command.  Quoted, one of them from each pair
        # should be passed through to the application layer.
        h = self.p.protocol

        L = [b"here are some bytes\xff\xff with an embedded IAC",
             b"and here is a test of a border escape\xff",
             b"\xff did you get that IAC?"]

        for b in L:
            self.p.dataReceived(b)

        self.assertEqual(h.bytes, b''.join(L).replace(b'\xff\xff', b'\xff'))

    def _simpleCommandTest(self, cmdName):
        # Send a single simple telnet command and make sure
        # it gets noticed and the appropriate method gets
        # called.
        h = self.p.protocol

        cmd = telnet.IAC + getattr(telnet, cmdName)
        L = [b"Here's some bytes, tra la la",
             b"But ono!" + cmd + b" an interrupt"]

        for b in L:
            self.p.dataReceived(b)

        self.assertEqual(h.calls, [cmdName])
        self.assertEqual(h.bytes, b''.join(L).replace(cmd, b''))

    def testInterrupt(self):
        self._simpleCommandTest("IP")

    def testNoOperation(self):
        self._simpleCommandTest("NOP")

    def testDataMark(self):
        self._simpleCommandTest("DM")

    def testBreak(self):
        self._simpleCommandTest("BRK")

    def testAbortOutput(self):
        self._simpleCommandTest("AO")

    def testAreYouThere(self):
        self._simpleCommandTest("AYT")

    def testEraseCharacter(self):
        self._simpleCommandTest("EC")

    def testEraseLine(self):
        self._simpleCommandTest("EL")

    def testGoAhead(self):
        self._simpleCommandTest("GA")

    def testSubnegotiation(self):
        # Send a subnegotiation command and make sure it gets
        # parsed and that the correct method is called.
        h = self.p.protocol

        cmd = telnet.IAC + telnet.SB + b'\x12hello world' + telnet.IAC + telnet.SE
        L = [b"These are some bytes but soon" + cmd,
             b"there will be some more"]

        for b in L:
            self.p.dataReceived(b)

        self.assertEqual(h.bytes, b''.join(L).replace(cmd, b''))
        self.assertEqual(h.subcmd, list(iterbytes(b"hello world")))

    def testSubnegotiationWithEmbeddedSE(self):
        # Send a subnegotiation command with an embedded SE.  Make sure
        # that SE gets passed to the correct method.
        h = self.p.protocol

        cmd = (telnet.IAC + telnet.SB +
               b'\x12' + telnet.SE +
               telnet.IAC + telnet.SE)

        L = [b"Some bytes are here" + cmd + b"and here",
             b"and here"]

        for b in L:
            self.p.dataReceived(b)

        self.assertEqual(h.bytes, b''.join(L).replace(cmd, b''))
        self.assertEqual(h.subcmd, [telnet.SE])

    def testBoundarySubnegotiation(self):
        # Send a subnegotiation command.  Split it at every possible byte boundary
        # and make sure it always gets parsed and that it is passed to the correct
        # method.
        cmd = (telnet.IAC + telnet.SB +
               b'\x12' + telnet.SE + b'hello' +
               telnet.IAC + telnet.SE)

        for i in range(len(cmd)):
            h = self.p.protocol = TestProtocol()
            h.makeConnection(self.p)

            a, b = cmd[:i], cmd[i:]
            L = [b"first part" + a,
                 b + b"last part"]

            for bytes in L:
                self.p.dataReceived(bytes)

            self.assertEqual(h.bytes, b''.join(L).replace(cmd, b''))
            self.assertEqual(h.subcmd, [telnet.SE] + list(iterbytes(b'hello')))

    def _enabledHelper(self, o, eL=[], eR=[], dL=[], dR=[]):
        self.assertEqual(o.enabledLocal, eL)
        self.assertEqual(o.enabledRemote, eR)
        self.assertEqual(o.disabledLocal, dL)
        self.assertEqual(o.disabledRemote, dR)

    def testRefuseWill(self):
        # Try to enable an option.  The server should refuse to enable it.
        cmd = telnet.IAC + telnet.WILL + b'\x12'

        bytes = b"surrounding bytes" + cmd + b"to spice things up"
        self.p.dataReceived(bytes)

        self.assertEqual(self.p.protocol.bytes, bytes.replace(cmd, b''))
        self.assertEqual(self.t.value(), telnet.IAC + telnet.DONT + b'\x12')
        self._enabledHelper(self.p.protocol)

    def testRefuseDo(self):
        # Try to enable an option.  The server should refuse to enable it.
        cmd = telnet.IAC + telnet.DO + b'\x12'

        bytes = b"surrounding bytes" + cmd + b"to spice things up"
        self.p.dataReceived(bytes)

        self.assertEqual(self.p.protocol.bytes, bytes.replace(cmd, b''))
        sel