summaryrefslogtreecommitdiff
path: root/cxmanage_api/tftp.py
blob: e3aaec3e6f723e1ca865686340dac2a88e91d585 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
"""Calxeda: tftp.py"""


# Copyright (c) 2012-2013, Calxeda Inc.
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of Calxeda Inc. nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
# THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
# DAMAGE.


import shutil
import socket
import logging
import traceback

from datetime import datetime, timedelta
from tftpy import TftpClient, TftpServer, setLogLevel
from threading import Thread
from cxmanage_api import temp_dir
from tftpy.TftpShared import TftpException


class InternalTftp(Thread):
    """Internally serves files using the `Trivial File Transfer Protocol \
<http://en.wikipedia.org/wiki/Trivial_File_Transfer_Protocol>`_.

    >>> # Typical instantiation ...
    >>> from cxmanage_api.tftp import InternalTftp
    >>> i_tftp = InternalTftp()
    >>> # Alternatively, you can specify an address or hostname ...
    >>> i_tftp = InternalTftp(ip_address='localhost')

    :param ip_address: Ip address for the Internal TFTP server to use.
    :type ip_address: string
    :param port: Port for the internal TFTP server.
    :type port: integer
    :param verbose: Flag to turn on additional messaging.
    :type verbose: boolean

    """
    _default = None

    @staticmethod
    def default():
        """ Return the default InternalTftp server """
        if InternalTftp._default == None:
            InternalTftp._default = InternalTftp()
        return InternalTftp._default

    def __init__(self, ip_address=None, port=0, verbose=False):
        super(InternalTftp, self).__init__()
        self.daemon = True

        self.tftp_dir = temp_dir()
        self.verbose = verbose

        self.server = TftpServer(tftproot=self.tftp_dir)
        self.ip_address = ip_address
        self.port = port
        self.start()

        # Get the port we actually hosted on
        if port == 0:
            deadline = datetime.now() + timedelta(seconds=10)
            while datetime.now() < deadline:
                try:
                    self.port = self.server.sock.getsockname()[1]
                    break
                except (AttributeError, socket.error):
                    pass
            else:
                # don't catch the error on our last attempt
                self.port = self.server.sock.getsockname()[1]

    def run(self):
        """ Run the server. Listens indefinitely. """
        if not self.verbose:
            setLogLevel(logging.CRITICAL)
        self.server.listen(listenport=self.port)

    def get_address(self, relative_host=None):
        """Returns the ipv4 address of this server.
        If a relative_host is specified, then we discover our address to them.

        >>> i_tftp.get_address(relative_host='10.10.14.150')
        'localhost'

        :param relative_host: Ip address to the relative host.
        :type relative_host: string

        :return: The ipv4 address of this InternalTftpServer.
        :rtype: string

        """
        if (self.ip_address != None):
            return self.ip_address
        elif (relative_host == None):
            return "localhost"
        else:
            sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            sock.connect((relative_host, self.port))
            ipv4 = sock.getsockname()[0]
            sock.close()
            return ipv4

    def get_file(self, src, dest):
        """Download a file from the tftp server to local_path.

        >>> i_tftp.get_file(src='remote_file_i_want.txt', dest='/local/path')

        :param src: Source file path on the tftp_server.
        :type src: string
        :param dest: Destination path (local machine) to copy the TFTP file to.
        :type dest: string

        """
        src = "%s/%s" % (self.tftp_dir, src)
        if (src != dest):
            try:
                # Ensure the file exists ...
                with open(src) as a_file:
                    a_file.close()
                shutil.copy(src, dest)

            except Exception:
                traceback.format_exc()
                raise

    def put_file(self, src, dest):
        """Upload a file from src to dest on the tftp server (path).

        >>> i_tftp.put_file(src='/local/file.txt', dest='remote_file_name.txt')

        :param src: Path to the local file to send to the TFTP server.
        :type src: string
        :param dest: Path to put the file to on the TFTP Server.
        :type dest: string

        """
        dest = "%s/%s" % (self.tftp_dir, dest)
        if (src != dest):
            try:
                # Ensure that the local file exists ...
                with open(src) as a_file:
                    a_file.close()
                shutil.copy(src, dest)
            except Exception:
                traceback.format_exc()
                raise


class ExternalTftp(object):
    """Defines a ExternalTftp object, which is actually TFTP client.

    >>> from cxmanage_api.tftp import ExternalTftp
    >>> e_tftp = ExternalTftp(ip_address='1.2.3.4')

    :param ip_address: Ip address of the TFTP server.
    :type ip_address: string
    :param port: Port to the External TFTP server.
    :type port: integer
    :param verbose: Flag to turn on verbose output (cmd/response).
    :type verbose: boolean

    """

    def __init__(self, ip_address, port=69, verbose=False):
        """Default constructor for this the ExternalTftp class."""
        self.ip_address = ip_address
        self.port = port
        self.verbose = verbose

        if not self.verbose:
            setLogLevel(logging.CRITICAL)

    def get_address(self, relative_host=None):
        """Return the ip address of the ExternalTftp server.

        >>> e_tftp.get_address()
        '1.2.3.4'

        :param relative_host: Unused parameter, for function signature.
        :type relative_host: None

        :returns: The ip address of the external TFTP server.
        :rtype: string

        """
        del relative_host  # Needed only for function signature.
        return self.ip_address

    def get_file(self, src, dest):
        """Download a file from the ExternalTftp Server.

        .. note::
            * TftpClient is not threadsafe, so we create a unique instance for
              each transfer.

        >>> e_tftp.get_file(src='remote_file_i_want.txt', dest='/local/path')

        :param src: The path to the file on the Tftp server.
        :type src: string
        :param dest: The local destination to copy the file to.
        :type dest: string

        :raises TftpException: If the file does not exist or cannot be obtained
                               from the TFTP server.
        :raises TftpException: If a TypeError is received from tftpy.

        """
        try:
            client = TftpClient(self.ip_address, self.port)
            client.download(output=dest, filename=src)
        except TftpException:
            if (self.verbose):
                traceback.format_exc()
            raise
        except TypeError:
            if (self.verbose):
                traceback.format_exc()
            raise TftpException("Failed download file from TFTP server")

    def put_file(self, src, dest):
        """Uploads a file to the tftp server.

        .. note::
            * TftpClient is not threadsafe, so we create a unique instance for
              each transfer.

        >>> e_tftp.put_file(src='local_file.txt', dest='remote_name.txt')

        :param src: Source file path (on your local machine).
        :type src: string
        :param dest: Destination path (on the TFTP server).
        :type dest: string

        :raises TftpException: If the file cannot be written to the TFTP server.
        :raises TftpException: If a TypeError is received from tftpy.

        """
        try:
            client = TftpClient(self.ip_address, self.port)
            client.upload(input=src, filename=dest)
        except TftpException:
            if (self.verbose):
                traceback.format_exc()
            raise
        except TypeError:
            if (self.verbose):
                traceback.format_exc()
            raise TftpException("Failed to upload file to TFTP server")


# End of file: ./tftp.py