Skip to content

Commit

Permalink
Use twisted.logger in conch instead of legacy logger
Browse files Browse the repository at this point in the history
  • Loading branch information
ryban committed Jul 15, 2020
1 parent 7adb468 commit 8ac48f2
Show file tree
Hide file tree
Showing 22 changed files with 168 additions and 181 deletions.
8 changes: 6 additions & 2 deletions src/twisted/conch/avatar.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,15 @@
from twisted.conch.error import ConchError
from twisted.conch.interfaces import IConchUser
from twisted.conch.ssh.connection import OPEN_UNKNOWN_CHANNEL_TYPE
from twisted.python import log
from twisted.python.compat import nativeString
from twisted.logger import Logger



@implementer(IConchUser)
class ConchUser:
log = Logger()

def __init__(self):
self.channelLookup = {}
self.subsystemLookup = {}
Expand All @@ -38,7 +41,8 @@ def lookupChannel(self, channelType, windowSize, maxPacket, data):


def lookupSubsystem(self, subsystem, data):
log.msg(repr(self.subsystemLookup))
self.log.debug('Subsystem lookup: {subsystem!r}',
subsystem=self.subsystemLookup)
klass = self.subsystemLookup.get(subsystem, None)
if not klass:
return False
Expand Down
16 changes: 8 additions & 8 deletions src/twisted/conch/checkers.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,13 @@
from twisted.cred.error import UnauthorizedLogin, UnhandledCredentials
from twisted.internet import defer
from twisted.python.compat import _keys, _b64decodebytes
from twisted.python import failure, reflect, log
from twisted.python import failure, reflect
from twisted.python.deprecate import deprecatedModuleAttribute
from twisted.python.util import runAsEffectiveUser
from twisted.python.filepath import FilePath
from twisted.logger import Logger

log = Logger()



Expand Down Expand Up @@ -178,8 +180,7 @@ def _cbRequestAvatarId(self, validKey, credentials):
pubKey = keys.Key.fromString(credentials.blob)
if pubKey.verify(credentials.signature, credentials.sigData):
return credentials.username
except: # any error should be treated as a failed login
log.err()
except Exception: # any error should be treated as a failed login
return failure.Failure(UnauthorizedLogin('error while verifying key'))
return failure.Failure(UnauthorizedLogin("unable to verify key"))

Expand Down Expand Up @@ -237,7 +238,7 @@ def checkKey(self, credentials):

def _ebRequestAvatarId(self, f):
if not f.check(UnauthorizedLogin):
log.msg(f)
log.error('Unauthorized login {error}', error=f.value)
return failure.Failure(UnauthorizedLogin("unable to get avatar id"))
return f

Expand Down Expand Up @@ -380,8 +381,8 @@ def readAuthorizedKeyFile(fileobj, parseKey=keys.Key.fromString):
try:
yield parseKey(line)
except keys.BadKeyError as e:
log.msg('Unable to parse line "{0}" as a key: {1!s}'
.format(line, e))
log.error('Unable to parse line {line!r} as a key: {error!s}',
line=line, error=e)



Expand Down Expand Up @@ -410,7 +411,7 @@ def _keysFromFilepaths(filepaths, parseKey):
for key in readAuthorizedKeyFile(f, parseKey):
yield key
except (IOError, OSError) as e:
log.msg("Unable to read {0}: {1!s}".format(fp.path, e))
log.error("Unable to read {path!r}: {error!s}", path=fp.path, error=e)



Expand Down Expand Up @@ -581,7 +582,6 @@ def _verifyKey(self, pubKey, credentials):
if pubKey.verify(credentials.signature, credentials.sigData):
return credentials.username
except: # Any error should be treated as a failed login
log.err()
raise UnauthorizedLogin('Error while verifying key')

raise UnauthorizedLogin("Key signature invalid.")
4 changes: 1 addition & 3 deletions src/twisted/conch/client/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,6 @@

from twisted.conch.ssh import agent, channel, keys
from twisted.internet import protocol, reactor
from twisted.python import log



class SSHAgentClient(agent.SSHAgentClient):
Expand All @@ -28,7 +26,7 @@ def getPublicKeys(self):


def _cbPublicKeys(self, blobcomm):
log.msg('got %i public keys' % len(blobcomm))
self.log.debug('got {num_keys} public keys', num_keys=len(blobcomm))
self.blobs = [x[0] for x in blobcomm]


Expand Down
9 changes: 3 additions & 6 deletions src/twisted/conch/client/default.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,6 @@
interact with a known_hosts database, use L{twisted.conch.client.knownhosts}.
"""


from twisted.python import log
from twisted.python.compat import (
nativeString, raw_input, _b64decodebytes as decodebytes)
from twisted.python.filepath import FilePath
Expand Down Expand Up @@ -168,7 +166,7 @@ def __init__(self, user, options, *args):

def serviceStarted(self):
if 'SSH_AUTH_SOCK' in os.environ and not self.options['noagent']:
log.msg('using agent')
self.log.debug('using SSH agent')
cc = protocol.ClientCreator(reactor, agent.SSHAgentClient)
d = cc.connectUNIX(os.environ['SSH_AUTH_SOCK'])
d.addCallback(self._setAgent)
Expand Down Expand Up @@ -239,12 +237,11 @@ def getPublicKey(self):
if key is not None:
return key
files = [x for x in self.options.identitys if x not in self.usedFiles]
log.msg(str(self.options.identitys))
log.msg(str(files))
self.log.debug('public key identities: {identities}\n{files}',
identities=self.options.identitys, files=files)
if not files:
return None
file = files[0]
log.msg(file)
self.usedFiles.append(file)
file = os.path.expanduser(file)
file += '.pub'
Expand Down
6 changes: 2 additions & 4 deletions src/twisted/conch/client/direct.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@
from twisted.internet import defer, protocol, reactor
from twisted.conch import error
from twisted.conch.ssh import transport
from twisted.python import log



class SSHClientFactory(protocol.ClientFactory):
Expand Down Expand Up @@ -78,7 +76,7 @@ def sendDisconnect(self, code, reason):


def receiveDebug(self, alwaysDisplay, message, lang):
log.msg('Received Debug Message: %s' % message)
self.log.debug('Received Debug Message: {message}', message=message)
if alwaysDisplay: # XXX what should happen here?
print(message)

Expand All @@ -89,7 +87,7 @@ def verifyHostKey(self, pubKey, fingerprint):


def setService(self, service):
log.msg('setting client server to %s' % service)
self.log.info('setting client server to {service}', service=service)
transport.SSHClientTransport.setService(self, service)
if service.name != 'ssh-userauth' and self.factory.d is not None:
d, self.factory.d = self.factory.d, None
Expand Down
6 changes: 4 additions & 2 deletions src/twisted/conch/client/knownhosts.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,12 @@
from twisted.conch.error import HostKeyChanged, UserRejectedKey, InvalidEntry
from twisted.conch.ssh.keys import Key, BadKeyError, FingerprintFormats
from twisted.internet import defer
from twisted.python import log
from twisted.python.compat import nativeString, unicode
from twisted.python.randbytes import secureRandom
from twisted.python.util import FancyEqMixin
from twisted.logger import Logger

log = Logger()


def _b64encode(s):
Expand Down Expand Up @@ -626,4 +628,4 @@ def warn(self, text):
with closing(self.opener()) as f:
f.write(text)
except:
log.err()
log.failure('Failed to write to console')
8 changes: 5 additions & 3 deletions src/twisted/conch/insults/helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,11 @@
from incremental import Version

from twisted.internet import defer, protocol, reactor
from twisted.python import log, _textattributes
from twisted.python import _textattributes
from twisted.python.compat import iterbytes
from twisted.python.deprecate import deprecated, deprecatedModuleAttribute
from twisted.conch.insults import insults
from twisted.logger import Logger

FOREGROUND = 30
BACKGROUND = 40
Expand Down Expand Up @@ -124,6 +125,7 @@ class TerminalBuffer(protocol.Protocol):

fill = b' '
void = object()
log = Logger()

def getCharacter(self, x, y):
return self.lines[y][x]
Expand Down Expand Up @@ -356,14 +358,14 @@ def selectGraphicRendition(self, *attributes):
try:
v = int(a)
except ValueError:
log.msg("Unknown graphic rendition attribute: " + repr(a))
self.log.error("Unknown graphic rendition attribute: {attr!r}", attr=a)
else:
if FOREGROUND <= v <= FOREGROUND + N_COLORS:
self.graphicRendition['foreground'] = v - FOREGROUND
elif BACKGROUND <= v <= BACKGROUND + N_COLORS:
self.graphicRendition['background'] = v - BACKGROUND
else:
log.msg("Unknown graphic rendition attribute: " + repr(a))
self.log.error("Unknown graphic rendition attribute: {attr!r}", attr=a)


def eraseLine(self):
Expand Down
5 changes: 2 additions & 3 deletions src/twisted/conch/openssh_compat/factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@

import os, errno

from twisted.python import log
from twisted.python.util import runAsEffectiveUser

from twisted.conch.ssh import keys, factory, common
Expand All @@ -36,7 +35,7 @@ def getPublicKeys(self):
t = common.getNS(k.blob())[0]
ks[t] = k
except Exception as e:
log.msg('bad public key file %s: %s' % (filename, e))
self.log.error('bad public key file {filename}: {error}', filename=filename, error=e)
return ks


Expand All @@ -59,7 +58,7 @@ def getPrivateKeys(self):
else:
raise
except Exception as e:
log.msg('bad private key file %s: %s' % (filename, e))
self.log.error('bad public key file {filename}: {error}', filename=filename, error=e)
else:
privateKeys[key.sshType()] = key
return privateKeys
Expand Down
7 changes: 5 additions & 2 deletions src/twisted/conch/recvline.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,9 @@

from twisted.conch.insults import insults, helper

from twisted.python import log, reflect
from twisted.python import reflect
from twisted.python.compat import iterbytes
from twisted.logger import Logger

_counters = {} # type: Dict[str, int]

Expand Down Expand Up @@ -409,6 +410,8 @@ class RecvLine(insults.TerminalProtocol):
pn = 0
_printableChars = string.printable.encode("ascii")

log = Logger()

def connectionMade(self):
# A list containing the characters making up the current line
self.lineBuffer = []
Expand Down Expand Up @@ -499,7 +502,7 @@ def keystrokeReceived(self, keyID, modifier):
elif keyID in self._printableChars:
self.characterReceived(keyID, False)
else:
log.msg("Received unhandled keyID: %r" % (keyID,))
self.log.warn("Received unhandled keyID: {keyID!r}", keyID=keyID)


def characterReceived(self, ch, moreCharactersComing):
Expand Down
33 changes: 11 additions & 22 deletions src/twisted/conch/ssh/channel.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,13 @@

from zope.interface import implementer

from twisted.python import log
from twisted.python.compat import nativeString, intToBytes
from twisted.internet import interfaces

from twisted.logger import Logger


@implementer(interfaces.ITransport)
class SSHChannel(log.Logger):
class SSHChannel(object):
"""
A class that represents a multiplexed channel over an SSH connection.
The channel has a local window which is the maximum amount of data it will
Expand Down Expand Up @@ -51,7 +50,7 @@ class SSHChannel(log.Logger):
@ivar remoteClosed: True if the other side isn't accepting more data.
@type remoteClosed: L{bool}
"""

log = Logger()
name = None # type: bytes # only needed for client channels

def __init__(self, localWindow=0, localMaxPacket=0,
Expand Down Expand Up @@ -92,24 +91,14 @@ def __bytes__(self):
b' rw ' + intToBytes(self.remoteWindowLeft) +
b')>')


def logPrefix(self):
id = (self.id is not None and str(self.id)) or "unknown"
name = self.name
if name:
name = nativeString(name)
return "SSHChannel %s (%s) on %s" % (name, id,
self.conn.logPrefix())


def channelOpen(self, specificData):
"""
Called when the channel is opened. specificData is any data that the
other side sent us when opening the channel.
@type specificData: L{bytes}
"""
log.msg('channel open')
self.log.info('channel open')


def openFailed(self, reason):
Expand All @@ -119,7 +108,7 @@ def openFailed(self, reason):
@type reason: L{error.ConchError}
"""
log.msg('other side refused open\nreason: %s'% reason)
self.log.error('other side refused open\nreason: {reason}', reason=reason)


def addWindowBytes(self, data):
Expand Down Expand Up @@ -159,7 +148,7 @@ def requestReceived(self, requestType, data):
f = getattr(self, 'request_%s'%foo, None)
if f:
return f(data)
log.msg('unhandled request for %s'%requestType)
self.log.info('unhandled request for {requestType}', requestType=requestType)
return 0


Expand All @@ -169,7 +158,7 @@ def dataReceived(self, data):
@type data: L{bytes}
"""
log.msg('got data %s'%repr(data))
self.log.debug('got data {data}', data=data)


def extReceived(self, dataType, data):
Expand All @@ -179,21 +168,21 @@ def extReceived(self, dataType, data):
@type dataType: L{int}
@type data: L{str}
"""
log.msg('got extended data %s %s'%(dataType, repr(data)))
self.log.debug('got extended data {dataType} {data!r}', dataType=dataType, data=data)


def eofReceived(self):
"""
Called when the other side will send no more data.
"""
log.msg('remote eof')
self.log.info('remote eof')


def closeReceived(self):
"""
Called when the other side has closed the channel.
"""
log.msg('remote close')
self.log.info('remote close')
self.loseConnection()


Expand All @@ -202,7 +191,7 @@ def closed(self):
Called when the channel is closed. This means that both our side and
the remote side have closed the channel.
"""
log.msg('closed')
self.log.info('closed')


def write(self, data):
Expand Down
Loading

0 comments on commit 8ac48f2

Please sign in to comment.