-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathtftptransfer.cpp
377 lines (293 loc) · 10.6 KB
/
tftptransfer.cpp
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
/*
* This file is part of PXEDHCP.
* Copyright 2013 A. Douglas Gale
*
* PXEDHCP is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* PXEDHCP is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include "tftptransfer.h"
#include <QFile>
#include <QFileInfo>
#include <QtEndian>
// DATA and ACK packets start with this structure
// Error packets do too, except "block" holds the error code
struct BlockHeader
{
quint16 opcode;
quint16 block;
};
TFTPTransfer::TFTPTransfer(QObject *parent)
: QObject(parent)
, sock(nullptr)
, blockSize(512)
, retransmitTimer(new QTimer(this))
, retransmitInterval(1000)
{
retransmitTimer->setSingleShot(true);
connect(retransmitTimer, SIGNAL(timeout()),
this, SLOT(OnRetransmitTimer()));
}
void TFTPTransfer::SendErrorPacket(QUdpSocket *target,
const QHostAddress &address, quint16 port,
quint16 errorCode, const QString &errorMessage)
{
QByteArray packet;
packet.resize(sizeof(BlockHeader) + errorMessage.length() + 1);
BlockHeader *header;
header = (BlockHeader*)packet.data();
header->opcode = qToBigEndian((quint16)ERROR);
header->block = qToBigEndian((quint16)errorCode);
memcpy((char*)(header+1), errorMessage.toLocal8Bit().constData(),
errorMessage.length() + 1);
quint16 sentSize = target->writeDatagram(packet, address, port);
if (sentSize != packet.size())
emit ErrorEvent("Outbound error packet truncated!");
}
void TFTPTransfer::SendErrorFileNotFound(QUdpSocket *target,
const QHostAddress &addr, quint16 port)
{
SendErrorPacket(target, addr, port, FILENOTFOUND, "File not found");
}
QString TFTPTransfer::TranslateFilename(
const QString &serverRoot, const char *filename)
{
QString result(filename);
result = result.replace(QChar('\\'), QChar('/'));
if (result.contains("/..") || result.contains("../"))
return "";
if (result[0] != '/')
result = serverRoot + '/' + result;
else
result = serverRoot + result;
return result;
}
bool TFTPTransfer::StartTransfer(QUdpSocket *,
const QHostAddress &addr, quint16 port,
quint16 opcode, const QString &serverRoot,
const TFTPServer::OptionList &options)
{
sock = new QUdpSocket(this);
connect(sock, SIGNAL(readyRead()), this, SLOT(OnPacketReceived()));
if (!sock->bind(0))
{
emit ErrorEvent("bind(0) failed!");
deleteLater();
return false;
}
if (opcode != RRQ)
{
emit ErrorEvent("opcode is not RRQ!");
SendErrorPacket(sock, addr, port,
ILLEGALOPERATION, "Unsupported operation");
deleteLater();
return false;
}
const char *requestFilename;
requestFilename = options[0].second;
// mode is ignored
//const char *mode;
//mode = options[1].second;
QString filename;
filename = TranslateFilename(serverRoot, requestFilename);
file = new QFile(filename, this);
if (!file)
{
emit ErrorEvent("Out of memory");
deleteLater();
return false;
}
if (!file->open(QFile::ReadOnly))
{
emit ErrorEvent(QString("File %1 not found: %2")
.arg(filename).arg(file->errorString()));
SendErrorFileNotFound(sock, addr, port);
deleteLater();
return false;
}
emit verboseEvent(QString("TFTP: File \"%1\" opened").arg(filename));
// File must be world readable
if ((file->permissions() & QFile::ReadOther) == 0)
{
SendErrorPacket(sock, addr, port, ACCESSVIOLATION, "Permission denied");
deleteLater();
return false;
}
// Prepare OACK
QByteArray oack;
oack.append((char)0);
oack.append((char)OACK);
const char *tsizeOption = TFTPServer::LookupOption(options, "tsize");
if (tsizeOption)
{
qint64 fileSize;
fileSize = file->size();
emit verboseEvent(QString("Response file size=%1").arg(fileSize));
oack.append(u8"tsize");
oack.append((char)0);
oack.append(QString("%1").arg(fileSize).toUtf8());
oack.append((char)0);
}
const char *blockSizeOption = TFTPServer::LookupOption(options, "blksize");
if (blockSizeOption)
{
blockSize = atoi(blockSizeOption);
emit verboseEvent(QString("Setting blksize to %1").arg(blockSize));
oack.append(u8"blksize");
oack.append((char)0);
oack.append(QString("%1").arg(blockSize).toUtf8());
oack.append((char)0);
}
const char *timeoutOption = TFTPServer::LookupOption(options, "timeout");
if (timeoutOption)
{
retransmitInterval = (unsigned char)timeoutOption[0];
// Clamp to valid range
if (retransmitInterval < 1)
retransmitInterval = 1;
if (retransmitInterval > 255)
retransmitInterval = 255;
emit verboseEvent(QString("Setting timeout to %1 seconds")
.arg(retransmitInterval));
oack.append(u8"timeout");
oack.append((char)0);
oack.append((char)retransmitInterval);
oack.append((char)0);
}
qint64 sentSize;
// Send OACK if we set any options
if (oack.size() > 2)
{
emit verboseEvent(QString("Sending OACK to %1").arg(blockSize));
sentSize = sock->writeDatagram(oack, addr, port);
if (sentSize != oack.size())
emit ErrorEvent("Outbound OACK packet truncated!");
}
clientAddr = addr;
clientPort = port;
// Size the packet buffer
sendBuffer.resize(sizeof(BlockHeader) + blockSize);
// Start at block 1
block = 1;
// Prepare packet
BlockHeader *header;
header = (BlockHeader*)sendBuffer.data();
header->opcode = qToBigEndian((quint16)DATA);
header->block = qToBigEndian(block);
// Read data directly into packet buffer
qint16 readSize;
readSize = file->read((char*)(header + 1), blockSize);
// Remember packet size for possible retransmit
sendSize = (quint16)(sizeof(BlockHeader) + readSize);
// Send initial packet if there wasn't an OACK sent
// (The client will send an ACK for block 0 to acknowledge OACK)
if (oack.size() <= 2)
{
// Send initial DATA datagram
sentSize = sock->writeDatagram((char*)header, sendSize,
clientAddr, clientPort);
if (sentSize != sendSize)
emit ErrorEvent("Outbound initial data packet truncated!");
}
return true;
}
void TFTPTransfer::OnPacketReceived()
{
QHostAddress sourceAddr;
quint16 sourcePort;
while (sock->hasPendingDatagrams())
{
int size = sock->pendingDatagramSize();
if (recvBuffer.size() < size)
recvBuffer.resize(size);
size = sock->readDatagram(recvBuffer.data(), size,
&sourceAddr, &sourcePort);
emit verboseEvent(QString("Datagram received, size=%1").arg(size));
// Drop packets from wrong client
if (sourceAddr != clientAddr || sourcePort != clientPort)
{
emit ErrorEvent("Dropped packet from wrong source");
continue;
}
BlockHeader header, *headerPtr;
headerPtr = (BlockHeader*)recvBuffer.data();
header.opcode = qFromBigEndian(headerPtr->opcode);
header.block = qFromBigEndian(headerPtr->block);
// Drop packets that are not acknowledgements
if (header.opcode != ACK)
{
emit ErrorEvent(QString("Receive error ACK,"
" opcode=%1, error=%2, message=%3")
.arg(header.opcode)
.arg(header.block)
.arg((char*)(headerPtr+1)));
sock->close();
retransmitTimer->stop();
deleteLater();
return;
}
// Remove spam message
emit verboseEvent(QString("Received ACK for %1").arg(header.block));
qint64 sentSize;
// Acknowledgement for the previous block is a request
// to retransmit
if (header.block == (quint16)(block-1))
{
// Retransmit current packet
sentSize = sock->writeDatagram(sendBuffer.data(), sendSize,
clientAddr, clientPort);
emit verboseEvent(QString("Retransmitted packet %1").arg(block));
retransmitTimer->start(retransmitInterval);
if (sentSize != sendSize)
emit ErrorEvent("Outbound retransmitted packet truncated!");
continue;
}
// Drop acknowledgements that are for wrong block
if (header.block != block)
{
// Reset retransmit timer
retransmitTimer->start(retransmitInterval);
emit verboseEvent("Dropped acknowledgement"
" for unexpected block number");
continue;
}
retransmitTimer->stop();
if (sendSize < sizeof(BlockHeader) + blockSize)
{
emit verboseEvent("Got ACK for last block, destroying transfer");
sock->close();
deleteLater();
return;
}
++block;
emit verboseEvent(QString("Sending block %1").arg(block));
// Prepare a new send packet
headerPtr = (BlockHeader*)sendBuffer.data();
headerPtr->opcode = qToBigEndian((quint16)DATA);
headerPtr->block = qToBigEndian(block);
qint64 readSize;
readSize = file->read((char*)(headerPtr+1), blockSize);
sendSize = sizeof(BlockHeader) + readSize;
sentSize = sock->writeDatagram((char*)sendBuffer.data(), sendSize,
clientAddr, clientPort);
if (sentSize != sendSize)
emit ErrorEvent("Outbound DATA packet truncated!");
retransmitTimer->start(retransmitInterval);
}
}
void TFTPTransfer::OnRetransmitTimer()
{
// Retransmit current packet
qint64 sentSize = sock->writeDatagram(sendBuffer.data(), sendSize,
clientAddr, clientPort);
emit verboseEvent(QString("Retransmitted packet %1").arg(block));
if (sentSize != sendSize)
emit ErrorEvent("Outbound retransmitted packet truncated!");
retransmitTimer->start(retransmitInterval);
}