/
LimitedSocket.cpp
executable file
·410 lines (332 loc) · 8.71 KB
/
LimitedSocket.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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
/*
FatRat download manager
http://fatrat.dolezel.info
Copyright (C) 2006-2008 Lubos Dolezel <lubos a dolezel.info>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
version 2 as published by the Free Software Foundation.
This program 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.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
USA.
*/
#include "LimitedSocket.h"
#include <QtDebug>
#include <QtNetwork/QHostAddress>
#include <QtNetwork/QNetworkProxy>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <QtNetwork/QTcpSocket>
#include <QtNetwork/QHostInfo>
using namespace std;
const int SPEED_SAMPLES = 7;
LimitedSocket::LimitedSocket()
: m_bAbort(false), m_nTransfered(0), m_nToTransfer(0),
m_nResume(0), m_nSegmentStart(-1), m_nSegmentEnd(-1), m_nSpeedLimit(0)
{
}
LimitedSocket::~LimitedSocket()
{
wait();
}
QString LimitedSocket::getErrorString(QAbstractSocket::SocketError err)
{
switch(err)
{
case QAbstractSocket::ConnectionRefusedError:
return tr("Connection refused");
case QAbstractSocket::RemoteHostClosedError:
return tr("Connection lost");
case QAbstractSocket::HostNotFoundError:
return tr("Host not found");
case QAbstractSocket::SocketAccessError:
return tr("Access denied");
case QAbstractSocket::SocketResourceError:
return tr("Socket resource error");
case QAbstractSocket::SocketTimeoutError:
return tr("Timeout");
case QAbstractSocket::DatagramTooLargeError:
return tr("Datagram too large");
case QAbstractSocket::NetworkError:
return tr("Network error");
case QAbstractSocket::AddressInUseError:
return tr("Address is already in use");
case QAbstractSocket::SocketAddressNotAvailableError:
return tr("Address is not available");
case QAbstractSocket::UnsupportedSocketOperationError:
return tr("Unsupported operation");
case QAbstractSocket::ProxyAuthenticationRequiredError:
return tr("The proxy requires authentication");
default:
return tr("Unknown error");
}
}
bool LimitedSocket::bindSocket(QAbstractSocket* sock, QHostAddress addr)
{
if(addr.isNull())
return true;
int error;
if(addr.protocol() == QAbstractSocket::IPv4Protocol)
{
sockaddr_in in;
memset(&in, 0, sizeof(in));
in.sin_addr.s_addr = addr.toIPv4Address();
in.sin_family = AF_INET;
error = ::bind(sock->socketDescriptor(), (sockaddr*) &in, sizeof(in));
}
else
{
sockaddr_in6 in6;
Q_IPV6ADDR a = addr.toIPv6Address();
memset(&in6, 0, sizeof(in6));
memcpy(in6.sin6_addr.s6_addr, a.c, 16);
in6.sin6_family = AF_INET6;
error = ::bind(sock->socketDescriptor(), (sockaddr*) &in6, sizeof(in6));
}
return !error;
}
bool LimitedSocket::open(QString file, bool bUpload)
{
QIODevice::OpenMode mode;
m_bUpload = bUpload;
if(bUpload)
mode = QIODevice::ReadOnly;
else
mode = (m_nSegmentStart < 0) ? QIODevice::Append : QIODevice::WriteOnly;
m_file.setFileName(file);
if(!m_file.open(mode))
{
qDebug() << "Failed to open file" << file;
m_strError = tr("Failed to open file");
return false;
}
if(m_nSegmentStart > 0)
m_file.seek(m_nSegmentStart);
return true;
}
void LimitedSocket::destroy()
{
m_bAbort = true;
if(isRunning())
connect(this, SIGNAL(finished()), this, SLOT(deleteLater()));
else
delete this;
}
QByteArray LimitedSocket::readLine()
{
while(true)
{
QByteArray array = getRemote()->readLine();
if(!array.isEmpty())
return array;
else
{
if(!getRemote()->waitForReadyRead(10000))
return QByteArray();
}
}
}
bool LimitedSocket::writeCycle()
{
int toRead;
QByteArray buffer;
QIODevice* pRemote = getRemote();
if(m_timer.isNull())
{
m_prevBytes = 0;
m_timer.start();
}
toRead = qMin<qint64>(1024*16, m_nToTransfer-m_nTransfered);
buffer = m_file.read(toRead);
if(buffer.size() < toRead)
{
m_strError = tr("Error reading file");
return false;
}
pRemote->write(buffer);
if(!pRemote->waitForBytesWritten(10000))
return false;
m_nTransfered += toRead;
//QTime now = QTime::currentTime();
int msecs;
qint64 bytes = m_nTransfered - m_prevBytes;
if((msecs = m_timer.elapsed()) > 1000)
{
m_statsLock.lockForWrite();
m_stats << QPair<int,qulonglong>(m_timer.restart(), bytes);
if(m_stats.size() > SPEED_SAMPLES)
m_stats.removeFirst();
m_statsLock.unlock();
m_prevBytes = m_nTransfered;
}
if(m_nSpeedLimit > 0 && bytes)
{
int sleeptime = bytes/(m_nSpeedLimit/1000) - msecs;
if(sleeptime > 0)
msleep(sleeptime*2);
}
return true;
}
bool LimitedSocket::readCycle()
{
QByteArray buffer;
bool bProblem = false;
QIODevice* pRemote = getRemote();
if(m_timer.isNull())
{
m_prevBytes = 0;
m_timer.start();
}
int limit = m_nSpeedLimit;
do
{
QByteArray buf;
qint64 available;
available = pRemote->bytesAvailable();
if(!available && !pRemote->waitForReadyRead(10000))
{
bProblem = true;
break;
}
qint64 toread = (limit) ? limit/2 : available;
if(m_nToTransfer && m_nToTransfer-m_nTransfered < toread)
toread = m_nToTransfer-m_nTransfered;
buf = pRemote->read(toread);
buffer += buf;
m_nTransfered += buf.size();
if(m_nTransfered >= m_nToTransfer && m_nToTransfer)
break;
}
while(buffer.size() < 1024);
m_file.write(buffer);
if(bProblem)
{
/*if(m_pSocket->state() == QAbstractSocket::ConnectedState) // timeout
m_strError = tr ( "Timeout" );
else if(m_pSocket->error() == QAbstractSocket::RemoteHostClosedError)
{
if(m_nToTransfer > m_nTransfered && m_nToTransfer)
{
qDebug() << "Remote host closed the connection";
m_strError = tr ( "Connection lost" );
}
}
else
{
m_strError = m_pSocket->errorString();
if ( m_strError.isEmpty() )
{
qDebug() << "Connection lost!";
m_strError = tr ( "Connection lost" );
}
}*/
}
else if(!m_bAbort)
{
// QTime now = QTime::currentTime();
qulonglong bnow = m_nTransfered;
int msecs;
qulonglong bytes = bnow - m_prevBytes;
if((msecs = m_timer.elapsed()) > 1000)
{
m_statsLock.lockForWrite();
m_stats << QPair<int,qulonglong> ( m_timer.restart(), bytes );
if(m_stats.size() > SPEED_SAMPLES)
m_stats.removeFirst();
m_statsLock.unlock();
m_prevBytes = bnow;
}
if(limit > 0 && bytes)
{
int sleeptime = bytes/ ( limit/1000 ) - msecs;
if(sleeptime > 0)
msleep(sleeptime*2);
}
}
return !bProblem;
}
int LimitedSocket::speed() const
{
int msecs = 0;
qulonglong bytes = 0;
m_statsLock.lockForRead();
for(int i=0;i<m_stats.size();i++)
{
msecs += m_stats[i].first;
bytes += m_stats[i].second;
}
m_statsLock.unlock();
if(!msecs)
return 0;
else
return 1000*bytes/msecs;
}
void LimitedSocket::doClose(QTcpSocket** sock)
{
if(!*sock)
return;
(*sock)->close();
QAbstractSocket::SocketState state = (*sock)->state();
if(state == QAbstractSocket::ConnectedState || state == QAbstractSocket::ClosingState)
(*sock)->waitForDisconnected(5000);
(*sock)->deleteLater();
(*sock) = 0;
}
void LimitedSocket::connectToHost(QTcpSocket* socket, QString host, quint16 port)
{
QList<QHostAddress> addr = performResolve(host);
if(addr.isEmpty())
throw tr("No address to connect to");
for(int i=0;i<addr.size();i++)
{
emit logMessage(tr("Connecting to %1").arg(addr[i].toString()));
socket->connectToHost(addr[i], port);
if(socket->waitForConnected())
return;
else
statusMessage(socket->errorString());
}
throw socket->errorString();
}
void LimitedSocket::connectToHost(QSslSocket* socket, QString host, quint16 port)
{
QList<QHostAddress> addr = performResolve(host);
if(addr.isEmpty())
throw tr("No address to connect to");
for(int i=0;i<addr.size();i++)
{
emit logMessage(tr("Connecting to %1").arg(addr[i].toString()));
socket->connectToHostEncrypted(addr[i].toString(), port);
if(socket->waitForConnected())
return;
else
statusMessage(socket->errorString());
}
throw socket->errorString();
}
QList<QHostAddress> LimitedSocket::performResolve(QString host, bool bPreferIPv6)
{
QHostInfo info = QHostInfo::fromName(host);
QList<QHostAddress> addresses, ip4, ip6;
addresses = info.addresses();
if(info.error() != QHostInfo::NoError)
throw info.errorString();
foreach(QHostAddress addr, addresses)
{
if(addr.protocol() == QAbstractSocket::IPv6Protocol)
ip6 << addr;
else if(addr.protocol() == QAbstractSocket::IPv4Protocol)
ip4 << addr;
}
addresses.clear();
if(bPreferIPv6)
addresses << ip6 << ip4;
else
addresses << ip4 << ip6;
return addresses;
}