summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMichael P. Soulier <msoulier@digitaltorque.ca>2021-10-21 11:30:06 -0400
committerMichael P. Soulier <msoulier@digitaltorque.ca>2021-10-21 11:30:06 -0400
commit77ba33dee44b3d889781db32cfcf99a4a2ada4dd (patch)
tree468ace4bd5361ec74f9f46e0057436efd8eb5d2e
parent6488895bf983ebb6c3d7a5da3a26b0b990391357 (diff)
parentd3a1753f08934929b8921fce9142c80ddd65d035 (diff)
downloadtftpy-77ba33dee44b3d889781db32cfcf99a4a2ada4dd.tar.gz
Merge remote-tracking branch 'BuhtigithuB/codebase-enhancements' into codebase
-rwxr-xr-xbin/tftpy_client.py9
-rwxr-xr-xbin/tftpy_server.py10
-rw-r--r--tftpy/TftpClient.py3
-rw-r--r--tftpy/TftpContexts.py51
-rw-r--r--tftpy/TftpPacketFactory.py1
-rw-r--r--tftpy/TftpPacketTypes.py12
-rw-r--r--tftpy/TftpServer.py62
-rw-r--r--tftpy/TftpShared.py7
-rw-r--r--tftpy/TftpStates.py55
-rw-r--r--tftpy/compat.py6
10 files changed, 121 insertions, 95 deletions
diff --git a/bin/tftpy_client.py b/bin/tftpy_client.py
index 12f38f7..40b6214 100755
--- a/bin/tftpy_client.py
+++ b/bin/tftpy_client.py
@@ -2,8 +2,11 @@
# vim: ts=4 sw=4 et ai:
# -*- coding: utf8 -*-
-import sys, logging, os
+import logging
+import os
+import sys
from optparse import OptionParser
+
import tftpy
log = logging.getLogger('tftpy')
@@ -16,8 +19,9 @@ default_formatter = logging.Formatter('[%(asctime)s] %(message)s')
handler.setFormatter(default_formatter)
log.addHandler(handler)
+
def main():
- usage=""
+ usage = ""
parser = OptionParser(usage=usage)
parser.add_option('-H',
'--host',
@@ -132,5 +136,6 @@ def main():
except KeyboardInterrupt:
pass
+
if __name__ == '__main__':
main()
diff --git a/bin/tftpy_server.py b/bin/tftpy_server.py
index a713563..66a5ee1 100755
--- a/bin/tftpy_server.py
+++ b/bin/tftpy_server.py
@@ -2,8 +2,10 @@
# vim: ts=4 sw=4 et ai:
# -*- coding: utf8 -*-
-import sys, logging
+import logging
+import sys
from optparse import OptionParser
+
import tftpy
log = logging.getLogger('tftpy')
@@ -16,8 +18,9 @@ default_formatter = logging.Formatter('[%(asctime)s] %(message)s')
handler.setFormatter(default_formatter)
log.addHandler(handler)
+
def main():
- usage=""
+ usage = ""
parser = OptionParser(usage=usage)
parser.add_option('-i',
'--ip',
@@ -52,7 +55,7 @@ def main():
debug_formatter = logging.Formatter('[%(asctime)s%(msecs)03d] %(levelname)s [%(name)s:%(lineno)s] %(message)s')
handler.setFormatter(debug_formatter)
elif options.quiet:
- log.setLevel(logging.WARN)
+ log.setLevel(logging.WARNING)
if not options.root:
parser.print_help()
@@ -67,5 +70,6 @@ def main():
except KeyboardInterrupt:
pass
+
if __name__ == '__main__':
main()
diff --git a/tftpy/TftpClient.py b/tftpy/TftpClient.py
index 8b215a3..6ef3578 100644
--- a/tftpy/TftpClient.py
+++ b/tftpy/TftpClient.py
@@ -13,12 +13,13 @@ from .TftpContexts import TftpContextClientDownload, TftpContextClientUpload
log = logging.getLogger('tftpy.TftpClient')
+
class TftpClient(TftpSession):
"""This class is an implementation of a tftp client. Once instantiated, a
download can be initiated via the download() method, or an upload via the
upload() method."""
- def __init__(self, host, port=69, options={}, localip = ""):
+ def __init__(self, host, port=69, options={}, localip=""):
TftpSession.__init__(self)
self.context = None
self.host = host
diff --git a/tftpy/TftpContexts.py b/tftpy/TftpContexts.py
index f01509e..da42a89 100644
--- a/tftpy/TftpContexts.py
+++ b/tftpy/TftpContexts.py
@@ -28,6 +28,7 @@ log = logging.getLogger('tftpy.TftpContext')
# Utility classes
###############################################################################
+
class TftpMetrics(object):
"""A class representing metrics of the transfer."""
def __init__(self):
@@ -74,10 +75,11 @@ class TftpMetrics(object):
# Context classes
###############################################################################
+
class TftpContext(object):
"""The base class of the contexts."""
- def __init__(self, host, port, timeout, retries=DEF_TIMEOUT_RETRIES, localip = ""):
+ def __init__(self, host, port, timeout, retries=DEF_TIMEOUT_RETRIES, localip=""):
"""Constructor for the base context, setting shared instance
variables."""
self.file_to_transfer = None
@@ -116,7 +118,7 @@ class TftpContext(object):
def __del__(self):
"""Simple destructor to try to call housekeeping in the end method if
- not called explicitely. Leaking file descriptors is not a good
+ not called explicitly. Leaking file descriptors is not a good
thing."""
self.end()
@@ -132,7 +134,7 @@ class TftpContext(object):
def end(self, close_fileobj=True):
"""Perform session cleanup, since the end method should always be
- called explicitely by the calling code, this works better than the
+ called explicitly by the calling code, this works better than the
destructor.
Set close_fileobj to False so fileobj can be returned open."""
log.debug("in TftpContext.end - closing socket")
@@ -142,12 +144,16 @@ class TftpContext(object):
self.fileobj.close()
def gethost(self):
- "Simple getter method for use in a property."
+ """
+ Simple getter method for use in a property.
+ """
return self.__host
def sethost(self, host):
- """Setter method that also sets the address property as a result
- of the host that is set."""
+ """
+ Setter method that also sets the address property as a result
+ of the host that is set.
+ """
self.__host = host
self.address = socket.gethostbyname(host)
@@ -165,8 +171,10 @@ class TftpContext(object):
next_block = property(getNextBlock, setNextBlock)
def cycle(self):
- """Here we wait for a response from the server after sending it
- something, and dispatch appropriate action to that response."""
+ """
+ Here we wait for a response from the server after sending it
+ something, and dispatch appropriate action to that response.
+ """
try:
(buffer, (raddress, rport)) = self.sock.recvfrom(MAX_BLKSIZE)
except socket.timeout:
@@ -175,7 +183,7 @@ class TftpContext(object):
# Ok, we've received a packet. Log it.
log.debug("Received %d bytes from %s:%s",
- len(buffer), raddress, rport)
+ len(buffer), raddress, rport)
# And update our last updated time.
self.last_update = time.time()
@@ -190,8 +198,7 @@ class TftpContext(object):
if self.tidport and self.tidport != rport:
log.warning("Received traffic from %s:%s but we're "
"connected to %s:%s. Discarding."
- % (raddress, rport,
- self.host, self.tidport))
+ % (raddress, rport, self.host, self.tidport))
# If there is a packethook defined, call it. We unconditionally
# pass all packets, it's up to the client to screen out different
@@ -206,6 +213,7 @@ class TftpContext(object):
# zero.
self.retry_count = 0
+
class TftpContextServer(TftpContext):
"""The context for the server."""
def __init__(self,
@@ -234,10 +242,12 @@ class TftpContextServer(TftpContext):
return "%s:%s %s" % (self.host, self.port, self.state)
def start(self, buffer):
- """Start the state cycle. Note that the server context receives an
+ """
+ Start the state cycle. Note that the server context receives an
initial packet in its start method. Also note that the server does not
loop on cycle(), as it expects the TftpServer object to manage
- that."""
+ that.
+ """
log.debug("In TftpContextServer.start")
self.metrics.start_time = time.time()
log.debug("Set metrics.start_time to %s", self.metrics.start_time)
@@ -260,6 +270,7 @@ class TftpContextServer(TftpContext):
log.debug("Set metrics.end_time to %s", self.metrics.end_time)
self.metrics.compute()
+
class TftpContextClientUpload(TftpContext):
"""The upload context for the client during an upload.
Note: If input is a hyphen, then we will use stdin."""
@@ -272,7 +283,7 @@ class TftpContextClientUpload(TftpContext):
packethook,
timeout,
retries=DEF_TIMEOUT_RETRIES,
- localip = ""):
+ localip=""):
TftpContext.__init__(self,
host,
port,
@@ -292,8 +303,7 @@ class TftpContextClientUpload(TftpContext):
self.fileobj = open(input, "rb")
log.debug("TftpContextClientUpload.__init__()")
- log.debug("file_to_transfer = %s, options = %s" %
- (self.file_to_transfer, self.options))
+ log.debug("file_to_transfer = %s, options = %s" % (self.file_to_transfer, self.options))
def __str__(self):
return "%s:%s %s" % (self.host, self.port, self.state)
@@ -309,7 +319,7 @@ class TftpContextClientUpload(TftpContext):
# FIXME: put this in a sendWRQ method?
pkt = TftpPacketWRQ()
pkt.filename = self.file_to_transfer
- pkt.mode = "octet" # FIXME - shouldn't hardcode this
+ pkt.mode = "octet" # FIXME - shouldn't hardcode this
pkt.options = self.options
self.sock.sendto(pkt.encode().buffer, (self.host, self.port))
self.next_block = 1
@@ -353,7 +363,7 @@ class TftpContextClientDownload(TftpContext):
packethook,
timeout,
retries=DEF_TIMEOUT_RETRIES,
- localip = ""):
+ localip=""):
TftpContext.__init__(self,
host,
port,
@@ -378,8 +388,7 @@ class TftpContextClientDownload(TftpContext):
self.fileobj = open(output, "wb")
log.debug("TftpContextClientDownload.__init__()")
- log.debug("file_to_transfer = %s, options = %s" %
- (self.file_to_transfer, self.options))
+ log.debug("file_to_transfer = %s, options = %s" % (self.file_to_transfer, self.options))
def __str__(self):
return "%s:%s %s" % (self.host, self.port, self.state)
@@ -396,7 +405,7 @@ class TftpContextClientDownload(TftpContext):
# FIXME: put this in a sendRRQ method?
pkt = TftpPacketRRQ()
pkt.filename = self.file_to_transfer
- pkt.mode = "octet" # FIXME - shouldn't hardcode this
+ pkt.mode = "octet" # FIXME - shouldn't hardcode this
pkt.options = self.options
self.sock.sendto(pkt.encode().buffer, (self.host, self.port))
self.next_block = 1
diff --git a/tftpy/TftpPacketFactory.py b/tftpy/TftpPacketFactory.py
index 41f39a9..64ce932 100644
--- a/tftpy/TftpPacketFactory.py
+++ b/tftpy/TftpPacketFactory.py
@@ -11,6 +11,7 @@ import logging
log = logging.getLogger('tftpy.TftpPacketFactory')
+
class TftpPacketFactory(object):
"""This class generates TftpPacket objects. It is responsible for parsing
raw buffers off of the wire and returning objects representing them, via
diff --git a/tftpy/TftpPacketTypes.py b/tftpy/TftpPacketTypes.py
index 3d3bdf8..d1361a6 100644
--- a/tftpy/TftpPacketTypes.py
+++ b/tftpy/TftpPacketTypes.py
@@ -11,12 +11,14 @@ from .TftpShared import *
log = logging.getLogger('tftpy.TftpPacketTypes')
+
class TftpSession(object):
"""This class is the base class for the tftp client and server. Any shared
code should be in this class."""
# FIXME: do we need this anymore?
pass
+
class TftpPacketWithOptions(object):
"""This class exists to permit some TftpPacket subclasses to share code
regarding options handling. It does not inherit from TftpPacket, as the
@@ -94,6 +96,7 @@ class TftpPacketWithOptions(object):
return options
+
class TftpPacket(object):
"""This class is the parent class of all tftp packet classes. It is an
abstract class, providing an interface, and should not be instantiated
@@ -120,6 +123,7 @@ class TftpPacket(object):
This is an abstract method."""
raise NotImplementedError("Abstract method")
+
class TftpPacketInitial(TftpPacket, TftpPacketWithOptions):
"""This class is a common parent class for the RRQ and WRQ packets, as
they share quite a bit of code."""
@@ -228,6 +232,7 @@ class TftpPacketInitial(TftpPacket, TftpPacketWithOptions):
log.debug("options dict is now %s", self.options)
return self
+
class TftpPacketRRQ(TftpPacketInitial):
"""
::
@@ -248,6 +253,7 @@ class TftpPacketRRQ(TftpPacketInitial):
s += '\n options = %s' % self.options
return s
+
class TftpPacketWRQ(TftpPacketInitial):
"""
::
@@ -268,6 +274,7 @@ class TftpPacketWRQ(TftpPacketInitial):
s += '\n options = %s' % self.options
return s
+
class TftpPacketDAT(TftpPacket):
"""
::
@@ -317,6 +324,7 @@ class TftpPacketDAT(TftpPacket):
log.debug("found %d bytes of data", len(self.data))
return self
+
class TftpPacketACK(TftpPacket):
"""
::
@@ -350,6 +358,7 @@ class TftpPacketACK(TftpPacket):
self.opcode, self.blocknumber)
return self
+
class TftpPacketERR(TftpPacket):
"""
::
@@ -408,7 +417,7 @@ class TftpPacketERR(TftpPacket):
return self
def decode(self):
- "Decode self.buffer, populating instance variables and return self."
+ """Decode self.buffer, populating instance variables and return self."""
buflen = len(self.buffer)
tftpassert(buflen >= 4, "malformed ERR packet, too short")
log.debug("Decoding ERR packet, length %s bytes", buflen)
@@ -428,6 +437,7 @@ class TftpPacketERR(TftpPacket):
% (self.errorcode, self.errmsg))
return self
+
class TftpPacketOACK(TftpPacket, TftpPacketWithOptions):
"""
::
diff --git a/tftpy/TftpServer.py b/tftpy/TftpServer.py
index 69adb1b..fe505c3 100644
--- a/tftpy/TftpServer.py
+++ b/tftpy/TftpServer.py
@@ -5,19 +5,22 @@ instance of the server, and then run the listen() method to listen for client
requests. Logging is performed via a standard logging object set in
TftpShared."""
-
-import socket, os, time
+import logging
+import os
import select
+import socket
import threading
-import logging
+import time
from errno import EINTR
-from .TftpShared import *
-from .TftpPacketTypes import *
-from .TftpPacketFactory import TftpPacketFactory
+
from .TftpContexts import TftpContextServer
+from .TftpPacketFactory import TftpPacketFactory
+from .TftpPacketTypes import *
+from .TftpShared import *
log = logging.getLogger('tftpy.TftpServer')
+
class TftpServer(TftpSession):
"""This class implements a tftp server object. Run the listen() method to
listen for client requests.
@@ -85,7 +88,8 @@ class TftpServer(TftpSession):
# Don't use new 2.5 ternary operator yet
# listenip = listenip if listenip else '0.0.0.0'
- if not listenip: listenip = '0.0.0.0'
+ if not listenip:
+ listenip = '0.0.0.0'
log.info("Server requested on ip %s, port %s" % (listenip, listenport))
try:
# FIXME - sockets should be non-blocking
@@ -103,8 +107,7 @@ class TftpServer(TftpSession):
log.debug("shutdown_immediately is %s" % self.shutdown_immediately)
log.debug("shutdown_gracefully is %s" % self.shutdown_gracefully)
if self.shutdown_immediately:
- log.warning("Shutting down now. Session count: %d" %
- len(self.sessions))
+ log.warning("Shutting down now. Session count: %d" % len(self.sessions))
self.sock.close()
for key in self.sessions:
self.sessions[key].end()
@@ -113,22 +116,19 @@ class TftpServer(TftpSession):
elif self.shutdown_gracefully:
if not self.sessions:
- log.warning("In graceful shutdown mode and all "
- "sessions complete.")
+ log.warning("In graceful shutdown mode and all sessions complete.")
self.sock.close()
break
# Build the inputlist array of sockets to select() on.
- inputlist = []
- inputlist.append(self.sock)
+ inputlist = [self.sock]
for key in self.sessions:
inputlist.append(self.sessions[key].sock)
# Block until some socket has input on it.
log.debug("Performing select on this inputlist: %s", inputlist)
try:
- readyinput, readyoutput, readyspecial = \
- select.select(inputlist, [], [], timeout)
+ readyinput, readyoutput, readyspecial = select.select(inputlist, [], [], timeout)
except select.error as err:
if err[0] == EINTR:
# Interrupted system call
@@ -149,17 +149,15 @@ class TftpServer(TftpSession):
log.debug("Read %d bytes", len(buffer))
if self.shutdown_gracefully:
- log.warning("Discarding data on main port, "
- "in graceful shutdown mode")
+ log.warning("Discarding data on main port, in graceful shutdown mode")
continue
# Forge a session key based on the client's IP and port,
# which should safely work through NAT.
key = "%s:%s" % (raddress, rport)
- if not key in self.sessions:
- log.debug("Creating new server context for "
- "session key = %s" % key)
+ if key not in self.sessions:
+ log.debug("Creating new server context for session key = %s" % key)
self.sessions[key] = TftpContextServer(raddress,
rport,
timeout,
@@ -171,11 +169,9 @@ class TftpServer(TftpSession):
self.sessions[key].start(buffer)
except TftpException as err:
deletion_list.append(key)
- log.error("Fatal exception thrown from "
- "session %s: %s" % (key, str(err)))
+ log.error("Fatal exception thrown from session %s: %s" % (key, str(err)))
else:
- log.warning("received traffic on main socket for "
- "existing session??")
+ log.warning("received traffic on main socket for existing session??")
log.info("Currently handling these sessions:")
for session_key, session in list(self.sessions.items()):
log.info(" %s" % session)
@@ -184,18 +180,15 @@ class TftpServer(TftpSession):
# Must find the owner of this traffic.
for key in self.sessions:
if readysock == self.sessions[key].sock:
- log.debug("Matched input to session key %s"
- % key)
+ log.debug("Matched input to session key %s" % key)
try:
self.sessions[key].cycle()
- if self.sessions[key].state == None:
+ if self.sessions[key].state is None:
log.info("Successful transfer.")
deletion_list.append(key)
except TftpException as err:
deletion_list.append(key)
- log.error("Fatal exception thrown from "
- "session %s: %s"
- % (key, str(err)))
+ log.error("Fatal exception thrown from session %s: %s" % (key, str(err)))
# Break out of for loop since we found the correct
# session.
break
@@ -212,8 +205,7 @@ class TftpServer(TftpSession):
log.error(str(err))
self.sessions[key].retry_count += 1
if self.sessions[key].retry_count >= self.sessions[key].retries:
- log.debug("hit max retries on %s, giving up" %
- self.sessions[key])
+ log.debug("hit max retries on %s, giving up" % self.sessions[key])
deletion_list.append(key)
else:
log.debug("resending on session %s" % self.sessions[key])
@@ -230,8 +222,7 @@ class TftpServer(TftpSession):
if metrics.duration == 0:
log.info("Duration too short, rate undetermined")
else:
- log.info("Transferred %d bytes in %.2f seconds"
- % (metrics.bytes, metrics.duration))
+ log.info("Transferred %d bytes in %.2f seconds" % (metrics.bytes, metrics.duration))
log.info("Average rate: %.2f kbps" % metrics.kbps)
log.info("%.2f bytes in resent data" % metrics.resent_bytes)
log.info("%d duplicate packets" % metrics.dupcount)
@@ -239,8 +230,7 @@ class TftpServer(TftpSession):
del self.sessions[key]
log.debug("Session list is now %s" % self.sessions)
else:
- log.warning(
- "Strange, session %s is not on the deletion list" % key)
+ log.warning("Strange, session %s is not on the deletion list" % key)
self.is_running.clear()
diff --git a/tftpy/TftpShared.py b/tftpy/TftpShared.py
index 7f618e9..452870c 100644
--- a/tftpy/TftpShared.py
+++ b/tftpy/TftpShared.py
@@ -2,8 +2,6 @@
# -*- coding: utf8 -*-
"""This module holds all objects shared by all other modules in tftpy."""
-
-
MIN_BLKSIZE = 8
DEF_BLKSIZE = 512
MAX_BLKSIZE = 65536
@@ -15,6 +13,7 @@ DEF_TFTP_PORT = 69
# A hook for deliberately introducing delay in testing.
DELAY_BLOCK = 0
+
def tftpassert(condition, msg):
"""This function is a simple utility that will check the condition
passed for a false state. If it finds one, it throws a TftpException
@@ -23,6 +22,7 @@ def tftpassert(condition, msg):
if not condition:
raise TftpException(msg)
+
class TftpErrors(object):
"""This class is a convenience for defining the common tftp error codes,
and making them more readable in the code."""
@@ -36,16 +36,19 @@ class TftpErrors(object):
NoSuchUser = 7
FailedNegotiation = 8
+
class TftpException(Exception):
"""This class is the parent class of all exceptions regarding the handling
of the TFTP protocol."""
pass
+
class TftpTimeout(TftpException):
"""This class represents a timeout error waiting for a response from the
other end."""
pass
+
class TftpFileNotFoundError(TftpException):
"""This class represents an error condition where we received a file
not found error."""
diff --git a/tftpy/TftpStates.py b/tftpy/TftpStates.py
index a72ab74..645993d 100644
--- a/tftpy/TftpStates.py
+++ b/tftpy/TftpStates.py
@@ -22,6 +22,7 @@ log = logging.getLogger('tftpy.TftpStates')
# State classes
###############################################################################
+
class TftpState(object):
"""The base class for the states."""
@@ -95,8 +96,7 @@ class TftpState(object):
buffer = self.context.fileobj.read(blksize)
log.debug("Read %d bytes into buffer", len(buffer))
if len(buffer) < blksize:
- log.info("Reached EOF on file %s"
- % self.context.file_to_transfer)
+ log.info("Reached EOF on file %s" % self.context.file_to_transfer)
finished = True
dat = TftpPacketDAT()
dat.data = buffer
@@ -131,7 +131,7 @@ class TftpState(object):
log.debug("In sendError, being asked to send error %d", errorcode)
errpkt = TftpPacketERR()
errpkt.errorcode = errorcode
- if self.context.tidport == None:
+ if self.context.tidport is None:
log.debug("Error packet received outside session. Discarding")
else:
self.context.sock.sendto(errpkt.encode().buffer,
@@ -151,9 +151,8 @@ class TftpState(object):
self.context.last_pkt = pkt
def resendLast(self):
- "Resend the last sent packet due to a timeout."
- log.warning("Resending packet %s on sessions %s"
- % (self.context.last_pkt, self))
+ """Resend the last sent packet due to a timeout."""
+ log.warning("Resending packet %s on sessions %s" % (self.context.last_pkt, self))
self.context.metrics.resent_bytes += len(self.context.last_pkt.buffer)
self.context.metrics.add_dup(self.context.last_pkt)
sendto_port = self.context.tidport
@@ -206,6 +205,7 @@ class TftpState(object):
# Default is to ack
return TftpStateExpectDAT(self.context)
+
class TftpServerState(TftpState):
"""The base class for server states."""
@@ -229,7 +229,7 @@ class TftpServerState(TftpState):
log.info("Setting tidport to %s" % rport)
log.debug("Setting default options, blksize")
- self.context.options = { 'blksize': DEF_BLKSIZE }
+ self.context.options = {'blksize': DEF_BLKSIZE}
if options:
log.debug("Options requested: %s", options)
@@ -239,19 +239,17 @@ class TftpServerState(TftpState):
# FIXME - only octet mode is supported at this time.
if pkt.mode != 'octet':
- #self.sendError(TftpErrors.IllegalTftpOp)
- #raise TftpException("Only octet transfers are supported at this time.")
+ # self.sendError(TftpErrors.IllegalTftpOp)
+ # raise TftpException("Only octet transfers are supported at this time.")
log.warning("Received non-octet mode request. I'll reply with binary data.")
# test host/port of client end
if self.context.host != raddress or self.context.port != rport:
self.sendError(TftpErrors.UnknownTID)
- log.error("Expected traffic from %s:%s but received it "
- "from %s:%s instead."
- % (self.context.host,
- self.context.port,
- raddress,
- rport))
+ log.error("Expected traffic from %s:%s but received it from %s:%s instead." % (self.context.host,
+ self.context.port,
+ raddress,
+ rport))
# FIXME: increment an error count?
# Return same state, we're still waiting for valid traffic.
return self
@@ -294,8 +292,9 @@ class TftpServerState(TftpState):
class TftpStateServerRecvRRQ(TftpServerState):
"""This class represents the state of the TFTP server when it has just
received an RRQ packet."""
+
def handle(self, pkt, raddress, rport):
- "Handle an initial RRQ packet as a server."
+ """Handle an initial RRQ packet as a server."""
log.debug("In TftpStateServerRecvRRQ.handle")
sendoack = self.serverInitial(pkt, raddress, rport)
path = self.full_path
@@ -346,6 +345,7 @@ class TftpStateServerRecvRRQ(TftpServerState):
# Note, we don't have to check any other states in this method, that's
# up to the caller.
+
class TftpStateServerRecvWRQ(TftpServerState):
"""This class represents the state of the TFTP server when it has just
received a WRQ packet."""
@@ -369,7 +369,7 @@ class TftpStateServerRecvWRQ(TftpServerState):
os.mkdir(current, 0o700)
def handle(self, pkt, raddress, rport):
- "Handle an initial WRQ packet as a server."
+ """Handle an initial WRQ packet as a server."""
log.debug("In TftpStateServerRecvWRQ.handle")
sendoack = self.serverInitial(pkt, raddress, rport)
path = self.full_path
@@ -384,8 +384,7 @@ class TftpStateServerRecvWRQ(TftpServerState):
log.info("Opening file %s for writing" % path)
if os.path.exists(path):
# FIXME: correct behavior?
- log.warning("File %s exists already, overwriting..." % (
- self.context.file_to_transfer))
+ log.warning("File %s exists already, overwriting..." % self.context.file_to_transfer)
# FIXME: I think we should upload to a temp file and not overwrite
# the existing file until the file is successfully uploaded.
self.make_subdirs()
@@ -409,6 +408,7 @@ class TftpStateServerRecvWRQ(TftpServerState):
# Note, we don't have to check any other states in this method, that's
# up to the caller.
+
class TftpStateServerStart(TftpState):
"""The start state for the server. This is a transitory state since at
this point we don't know if we're handling an upload or a download. We
@@ -430,13 +430,14 @@ class TftpStateServerStart(TftpState):
self.sendError(TftpErrors.IllegalTftpOp)
raise TftpException("Invalid packet to begin up/download: %s" % pkt)
+
class TftpStateExpectACK(TftpState):
"""This class represents the state of the transfer when a DAT was just
sent, and we are waiting for an ACK from the server. This class is the
same one used by the client during the upload, and the server during the
download."""
def handle(self, pkt, raddress, rport):
- "Handle a packet, hopefully an ACK since we just sent a DAT."
+ """Handle a packet, hopefully an ACK since we just sent a DAT."""
if isinstance(pkt, TftpPacketACK):
log.debug("Received ACK for packet %d" % pkt.blocknumber)
# Is this an ack to the one we just sent?
@@ -447,18 +448,15 @@ class TftpStateExpectACK(TftpState):
else:
log.debug("Good ACK, sending next DAT")
self.context.next_block += 1
- log.debug("Incremented next_block to %d",
- self.context.next_block)
+ log.debug("Incremented next_block to %d", self.context.next_block)
self.context.pending_complete = self.sendDAT()
elif pkt.blocknumber < self.context.next_block:
- log.warning("Received duplicate ACK for block %d"
- % pkt.blocknumber)
+ log.warning("Received duplicate ACK for block %d" % pkt.blocknumber)
self.context.metrics.add_dup(pkt)
else:
- log.warning("Oooh, time warp. Received ACK to packet we "
- "didn't send yet. Discarding.")
+ log.warning("Oooh, time warp. Received ACK to packet we didn't send yet. Discarding.")
self.context.metrics.errors += 1
return self
elif isinstance(pkt, TftpPacketERR):
@@ -468,6 +466,7 @@ class TftpStateExpectACK(TftpState):
log.warning("Discarding unsupported packet: %s" % str(pkt))
return self
+
class TftpStateExpectDAT(TftpState):
"""Just sent an ACK packet. Waiting for DAT."""
def handle(self, pkt, raddress, rport):
@@ -493,6 +492,7 @@ class TftpStateExpectDAT(TftpState):
self.sendError(TftpErrors.IllegalTftpOp)
raise TftpException("Received unknown packet type from peer: " + str(pkt))
+
class TftpStateSentWRQ(TftpState):
"""Just sent an WRQ packet for an upload."""
def handle(self, pkt, raddress, rport):
@@ -551,6 +551,7 @@ class TftpStateSentWRQ(TftpState):
# By default, no state change.
return self
+
class TftpStateSentRRQ(TftpState):
"""Just sent an RRQ packet."""
def handle(self, pkt, raddress, rport):
@@ -582,7 +583,7 @@ class TftpStateSentRRQ(TftpState):
log.info("Received DAT from server")
if self.context.options:
log.info("Server ignored options, falling back to defaults")
- self.context.options = { 'blksize': DEF_BLKSIZE }
+ self.context.options = {'blksize': DEF_BLKSIZE}
return self.handleDat(pkt)
# Every other packet type is a problem.
diff --git a/tftpy/compat.py b/tftpy/compat.py
index 0049396..ce8ffbb 100644
--- a/tftpy/compat.py
+++ b/tftpy/compat.py
@@ -1,15 +1,17 @@
import sys
+
def binary_stdin():
"""
Get a file object for reading binary bytes from stdin instead of text.
Compatible with Py2/3, POSIX & win32.
Credits: https://stackoverflow.com/a/38939320/531179 (CC BY-SA 3.0)
"""
- if hasattr(sys.stdin, 'buffer'): # Py3+
+ if hasattr(sys.stdin, 'buffer'): # Py3+
return sys.stdin.buffer
else:
if sys.platform == 'win32':
- import os, msvcrt
+ import os
+ import msvcrt
msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
return sys.stdin