This file is indexed.

/usr/share/pyshared/tftp/session.py is in python-txtftp 0.1~bzr38-0ubuntu2.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  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
279
280
'''
@author: shylent
'''
from tftp.datagram import (ACKDatagram, ERRORDatagram, OP_DATA, OP_ERROR, ERR_ILLEGAL_OP,
    ERR_DISK_FULL, OP_ACK, DATADatagram, ERR_NOT_DEFINED,)
from tftp.util import SequentialCall
from twisted.internet import reactor
from twisted.internet.defer import maybeDeferred
from twisted.internet.protocol import DatagramProtocol
from twisted.python import log

MAX_BLOCK_SIZE = 1400


class WriteSession(DatagramProtocol):
    """Represents a transfer, during which we write to a local file. If we are a
    server, this means, that we received a WRQ (write request). If we are a client,
    this means, that we have requested a read from a remote server.

    @cvar block_size: Expected block size. If a data chunk is received and its length
    is less, than C{block_size}, it is assumed that that data chunk is the last in the
    transfer. Default: 512 (as per U{RFC1350<http://tools.ietf.org/html/rfc1350>})
    @type block_size: C{int}.

    @cvar timeout: An iterable, that yields timeout values for every subsequent
    ACKDatagram, that we've sent, that is not followed by the next data chunk.
    When (if) the iterable is exhausted, the transfer is considered failed.
    @type timeout: any iterable

    @ivar started: whether or not this protocol has started
    @type started: C{bool}

    """

    block_size = 512
    timeout = (1, 1, 1, 1, 1, 1)
    tsize = None

    def __init__(self, writer, _clock=None):
        self.writer = writer
        self.blocknum = 0
        self.completed = False
        self.started = False
        self.timeout_watchdog = None
        if _clock is None:
            self._clock = reactor
        else:
            self._clock = _clock

    def cancel(self):
        """Cancel this session, discard any data, that was collected
        and give up the connector.

        """
        if self.timeout_watchdog is not None and self.timeout_watchdog.active():
            self.timeout_watchdog.cancel()
        self.writer.cancel()
        self.transport.stopListening()

    def startProtocol(self):
        self.started = True

    def connectionRefused(self):
        if not self.completed:
            self.writer.cancel()
        self.transport.stopListening()

    def datagramReceived(self, datagram):
        if datagram.opcode == OP_DATA:
            return self.tftp_DATA(datagram)
        elif datagram.opcode == OP_ERROR:
            log.msg("Got error: %s" % datagram)
            self.cancel()

    def tftp_DATA(self, datagram):
        """Handle incoming DATA TFTP datagram

        @type datagram: L{DATADatagram}

        """
        next_blocknum = self.blocknum + 1
        if datagram.blocknum < next_blocknum:
            self.transport.write(ACKDatagram(datagram.blocknum).to_wire())
        elif datagram.blocknum == next_blocknum:
            if self.completed:
                self.transport.write(ERRORDatagram.from_code(
                    ERR_ILLEGAL_OP, "Transfer already finished").to_wire())
            else:
                return self.nextBlock(datagram)
        else:
            self.transport.write(ERRORDatagram.from_code(
                ERR_ILLEGAL_OP, "Block number mismatch").to_wire())

    def nextBlock(self, datagram):
        """Handle fresh data, attempt to write it to backend

        @type datagram: L{DATADatagram}

        """
        if self.timeout_watchdog is not None and self.timeout_watchdog.active():
            self.timeout_watchdog.cancel()
        self.blocknum += 1
        d = maybeDeferred(self.writer.write, datagram.data)
        d.addCallbacks(callback=self.blockWriteSuccess, callbackArgs=[datagram, ],
                       errback=self.blockWriteFailure)
        return d

    def blockWriteSuccess(self, ign, datagram):
        """The write was successful, respond with ACK for current block number

        If this is the last chunk (received data length < block size), the protocol
        will keep running until the end of current timeout period, so we can respond
        to any duplicates.

        @type datagram: L{DATADatagram}

        """
        bytes = ACKDatagram(datagram.blocknum).to_wire()
        self.timeout_watchdog = SequentialCall.run(self.timeout[:-1],
            callable=self.sendData, callable_args=[bytes, ],
            on_timeout=lambda: self._clock.callLater(self.timeout[-1], self.timedOut),
            run_now=True,
            _clock=self._clock
        )
        if len(datagram.data) < self.block_size:
            self.completed = True
            self.writer.finish()
            # TODO: If self.tsize is not None, compare it with the actual
            # count of bytes written. Log if there's a mismatch. Should it
            # also emit an error datagram?

    def blockWriteFailure(self, failure):
        """Write failed"""
        log.err(failure)
        self.transport.write(ERRORDatagram.from_code(ERR_DISK_FULL).to_wire())
        self.cancel()

    def timedOut(self):
        """Called when the protocol has timed out. Let the backend know, if the
        the transfer was successful.

        """
        if not self.completed:
            log.msg("Timed out while waiting for next block")
            self.writer.cancel()
        else:
            log.msg("Timed out after a successful transfer")
        self.transport.stopListening()

    def sendData(self, bytes):
        """Send data to the remote peer

        @param bytes: bytes to send
        @type bytes: C{str}

        """
        self.transport.write(bytes)


class ReadSession(DatagramProtocol):
    """Represents a transfer, during which we read from a local file
    (and write to the network). If we are a server, this means, that we've received
    a RRQ (read request). If we are a client, this means that we've requested to
    write to a remote server.

    @cvar block_size: The data will be sent in chunks of this size. If we send
    a chunk with the size < C{block_size}, the transfer will end.
    Default: 512 (as per U{RFC1350<http://tools.ietf.org/html/rfc1350>})
    @type block_size: C{int}

    @cvar timeout: An iterable, that yields timeout values for every subsequent
    unacknowledged DATADatagram, that we've sent. When (if) the iterable is exhausted,
    the transfer is considered failed.
    @type timeout: any iterable

    @ivar started: whether or not this protocol has started
    @type started: C{bool}

    """
    block_size = 512
    timeout = (1, 1, 1, 1, 1, 1)

    def __init__(self, reader, _clock=None):
        self.reader = reader
        self.blocknum = 0
        self.started = False
        self.completed = False
        self.timeout_watchdog = None
        if _clock is None:
            self._clock = reactor
        else:
            self._clock = _clock

    def cancel(self):
        """Tell the reader to give up the resources. Stop the timeout cycle
        and disconnect the transport.

        """
        self.reader.finish()
        if self.timeout_watchdog is not None and self.timeout_watchdog.active():
            self.timeout_watchdog.cancel()
        self.transport.stopListening()

    def startProtocol(self):
        self.started = True

    def connectionRefused(self):
        self.finish()

    def datagramReceived(self, datagram):
        if datagram.opcode == OP_ACK:
            return self.tftp_ACK(datagram)
        elif datagram.opcode == OP_ERROR:
            log.msg("Got error: %s" % datagram)
            self.cancel()

    def tftp_ACK(self, datagram):
        """Handle the incoming ACK TFTP datagram.

        @type datagram: L{ACKDatagram}

        """
        if datagram.blocknum < self.blocknum:
            log.msg("Duplicate ACK for blocknum %s" % datagram.blocknum)
        elif datagram.blocknum == self.blocknum:
            if self.timeout_watchdog is not None and self.timeout_watchdog.active():
                self.timeout_watchdog.cancel()
            if self.completed:
                log.msg("Final ACK received, transfer successful")
                self.cancel()
            else:
                return self.nextBlock()
        else:
            self.transport.write(ERRORDatagram.from_code(
                ERR_ILLEGAL_OP, "Block number mismatch").to_wire())

    def nextBlock(self):
        """ACK datagram for the previous block has been received. Attempt to read
        the next block, that will be sent.

        """
        self.blocknum += 1
        d = maybeDeferred(self.reader.read, self.block_size)
        d.addCallbacks(callback=self.dataFromReader, errback=self.readFailed)
        return d

    def dataFromReader(self, data):
        """Got data from the reader. Send it to the network and start the timeout
        cycle.

        """
        if len(data) < self.block_size:
            self.completed = True
        bytes = DATADatagram(self.blocknum, data).to_wire()
        self.timeout_watchdog = SequentialCall.run(self.timeout[:-1],
            callable=self.sendData, callable_args=[bytes, ],
            on_timeout=lambda: self._clock.callLater(self.timeout[-1], self.timedOut),
            run_now=True,
            _clock=self._clock
        )

    def readFailed(self, fail):
        """The reader reported an error. Notify the remote end and cancel the transfer"""
        log.err(fail)
        self.transport.write(ERRORDatagram.from_code(ERR_NOT_DEFINED, "Read failed").to_wire())
        self.cancel()

    def timedOut(self):
        """Timeout iterable has been exhausted. End the transfer"""
        log.msg("Session timed out, last wait was %s seconds long" % self.timeout[-1])
        self.cancel()

    def sendData(self, bytes):
        """Send data to the remote peer

        @param bytes: bytes to send
        @type bytes: C{str}

        """
        self.transport.write(bytes)