This repository has been archived by the owner on May 8, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 16
/
duktoprotocol.cpp
842 lines (724 loc) · 25.9 KB
/
duktoprotocol.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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
/* DUKTO - A simple, fast and multi-platform file transfer tool for LAN users
* Copyright (C) 2011 Emanuele Colombo
*
* This program 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 2 of the License, or
* (at your option) any later version.
*
* 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include "duktoprotocol.h"
#if defined(Q_OS_WIN)
#include <windows.h>
#endif
#include <QStringList>
#include <QFileInfo>
#include <QDir>
#include <QNetworkInterface>
#include <QTimer>
#include "platform.h"
#define DEFAULT_UDP_PORT 4644
#define DEFAULT_TCP_PORT 4644
enum MSG_TYPE {
MSG_HELLO_BROADCAST = 0x01,
MSG_HELLO_UNICAST = 0x02,
MSG_GOODBYE = 0x03,
MSG_HELLO_PORT_BROADCAST = 0x04,
MSG_HELLO_PORT_UNICAST = 0x05
};
DuktoProtocol::DuktoProtocol()
: mSocket(NULL), mTcpServer(NULL), mCurrentSocket(NULL),
mCurrentFile(NULL), mFilesToSend(NULL)
{
mLocalUdpPort = DEFAULT_UDP_PORT;
mLocalTcpPort = DEFAULT_TCP_PORT;
mIsSending = false;
mIsReceiving = false;
mSendingScreen = false;
}
DuktoProtocol::~DuktoProtocol()
{
if (mCurrentSocket) delete mCurrentSocket;
if (mSocket) delete mSocket;
if (mTcpServer) delete mTcpServer;
if (mCurrentFile) delete mCurrentFile;
}
void DuktoProtocol::initialize()
{
mSocket = new QUdpSocket(this);
mSocket->bind(QHostAddress::Any, mLocalUdpPort);
connect(mSocket, SIGNAL(readyRead()), this, SLOT(newUdpData()));
mTcpServer = new QTcpServer(this);
mTcpServer->listen(QHostAddress::Any, mLocalTcpPort);
connect(mTcpServer, SIGNAL(newConnection()), this, SLOT(newIncomingConnection()));
}
void DuktoProtocol::setPorts(qint16 udp, qint16 tcp)
{
mLocalUdpPort = udp;
mLocalTcpPort = tcp;
}
QString DuktoProtocol::getSystemSignature()
{
static QString signature;
if (!signature.isEmpty()) return signature;
signature = Platform::getSystemUsername()
+ " at " + Platform::getHostname()
+ " (" + Platform::getPlatformName() + ")";
return signature;
}
void DuktoProtocol::sayHello(QHostAddress dest)
{
sayHello(dest, mLocalUdpPort);
}
void DuktoProtocol::sayHello(QHostAddress dest, qint16 port)
{
// Preparazione pacchetto
QByteArray packet;
if ((port == DEFAULT_UDP_PORT) && (mLocalUdpPort == DEFAULT_UDP_PORT))
{
if (dest == QHostAddress::Broadcast)
packet.append(MSG_HELLO_BROADCAST);
else
packet.append(MSG_HELLO_UNICAST);
}
else
{
if (dest == QHostAddress::Broadcast)
packet.append(MSG_HELLO_PORT_BROADCAST);
else
packet.append(MSG_HELLO_PORT_BROADCAST);
packet.append((char*)&mLocalUdpPort, sizeof(qint16));
}
packet.append(getSystemSignature());
// Invio pacchetto
if (dest == QHostAddress::Broadcast) {
QList<qint16> ports;
ports.append(DEFAULT_UDP_PORT);
if (port != DEFAULT_UDP_PORT)
ports.append(port);
sendToAllBroadcast(packet, ports);
}
else
mSocket->writeDatagram(packet.data(), packet.length(), dest, port);
}
void DuktoProtocol::sayGoodbye()
{
// Create packet
QByteArray packet;
packet.append(MSG_GOODBYE);
// Look for all the discovered ports
QList<qint16> ports;
ports.append(mLocalUdpPort);
if (mLocalUdpPort != DEFAULT_UDP_PORT) ports.append(DEFAULT_UDP_PORT);
QList<Peer> values = mPeers.values();
for(QList<Peer>::const_iterator p = values.constBegin(); p != values.constEnd(); ++p)
if(!ports.contains(p->port))
ports.append(p->port);
// Send broadcast message to all discovered ports
sendToAllBroadcast(packet, ports);
}
void DuktoProtocol::newUdpData()
{
while (mSocket->hasPendingDatagrams()) {
QByteArray datagram;
datagram.resize(65536); // Theoretical max length in IPv4
QHostAddress sender;
quint16 senderPort;
int size = mSocket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);
datagram.resize(size);
handleMessage(datagram, sender);
}
}
void DuktoProtocol::handleMessage(QByteArray &data, QHostAddress &sender)
{
char msgtype = data.at(0);
switch(msgtype)
{
case MSG_HELLO_BROADCAST:
case MSG_HELLO_UNICAST:
data.remove(0, 1);
if (data != getSystemSignature()) {
mPeers[sender.toString()] = Peer(sender, QString::fromUtf8(data), DEFAULT_UDP_PORT);
if (msgtype == MSG_HELLO_BROADCAST) sayHello(sender, DEFAULT_UDP_PORT);
emit peerListAdded(mPeers[sender.toString()]);
}
break;
case MSG_GOODBYE:
emit peerListRemoved(mPeers[sender.toString()]);
mPeers.remove(sender.toString());
break;
case MSG_HELLO_PORT_BROADCAST:
case MSG_HELLO_PORT_UNICAST:
data.remove(0, 1);
qint16 port = *((qint16*) data.constData());
data.remove(0, 2);
if (data != getSystemSignature()) {
mPeers[sender.toString()] = Peer(sender, QString::fromUtf8(data), port);
if (msgtype == MSG_HELLO_PORT_BROADCAST) sayHello(sender, port);
emit peerListAdded(mPeers[sender.toString()]);
}
break;
}
}
// Richiesta connessione TCP in ingresso
void DuktoProtocol::newIncomingConnection()
{
// Recieve connection
QTcpSocket* s = mTcpServer->nextPendingConnection();
if(s == NULL) return;
// If we are already recieving or sending
// Pending header connection (timeout 10 sec)
if ((mIsReceiving | mIsSending) || !s->waitForReadyRead(10000))
{
s->close();
delete s;
return;
}
// Update GUI
receiveFileStart(s->peerAddress().toString());
// set current TCP socket
mCurrentSocket = s;
// Register socket's event handlers
connect(mCurrentSocket, SIGNAL(readyRead()), this, SLOT(readNewData()), Qt::DirectConnection);
connect(mCurrentSocket, SIGNAL(disconnected()), this, SLOT(closedConnectionTmp()), Qt::QueuedConnection);
// Initialize variables
mIsReceiving = true;
mTotalReceivedData = 0;
mElementSize = -1;
mReceivedFiles = new QStringList();
mRootFolderName.clear();
mRootFolderRenamed.clear();
mReceivingText = false;
mRecvStatus = FILENAME;
// -- Reading General header --
// Entities number to receive
mCurrentSocket->read((char*) &mElementsToReceiveCount, sizeof(qint64));
// total size
mCurrentSocket->read((char*) &mTotalSize, sizeof(qint64));
// Start reading data on file
readNewData();
}
// Processo di lettura principale
void DuktoProtocol::readNewData()
{
// Fino a che ci sono dati da leggere
while (mCurrentSocket->bytesAvailable() > 0)
{
// In base allo stato in cui mi trovo leggo quello che mi aspetto
switch (mRecvStatus)
{
case FILENAME:
{
char c;
while (true) {
if (mCurrentSocket->read(&c, sizeof(c)) < 1) return;
if (c == '\0')
{
mRecvStatus = FILESIZE;
break;
}
mPartialName.append(c);
}
break;
}
case FILESIZE:
{
if(mCurrentSocket->bytesAvailable() < (int)sizeof(qint64)) return;
mCurrentSocket->read((char*) &mElementSize, sizeof(qint64));
mElementReceivedData = 0;
QString name = QString::fromUtf8(mPartialName);
mPartialName.clear();
// Se l'elemento corrente è una cartella, la creo e passo all'elemento successivo
if (mElementSize == -1)
{
// Verifico il nome della cartella "root"
// Se non ho ancora trattato questa root, lo faccio ora
if (mRootFolderName != name.section("/", 0, 0)) {
// Verifico se ho già una cartella con questo nome
// nel caso trovo un nome alternativo
int i = 2;
QString originalName = name;
while (QFile::exists(name))
name = originalName + " (" + QString::number(i++) + ")";
mRootFolderName = originalName;
mRootFolderRenamed = name;
mReceivedFiles->append(name);
}
// Se invece l'ho già trattata, allora rinomino questo percorso
else if (mRootFolderName != mRootFolderRenamed)
name = name.replace(0, name.indexOf('/'), mRootFolderRenamed);
// Creo la cartella
if (!QDir(".").mkpath(name))
{
emit receiveFileCancelled();
// Chiusura socket
if (mCurrentSocket)
{
mCurrentSocket->disconnect();
mCurrentSocket->disconnectFromHost();
mCurrentSocket->close();
mCurrentSocket->deleteLater();
mCurrentSocket = NULL;
}
// Rilascio memoria
delete mReceivedFiles;
mReceivedFiles = NULL;
// Impostazione stato
mIsReceiving = false;
return;
}
mRecvStatus = FILENAME;
break;
}
// Potrebbe essere un invio di testo
else if (name == "___DUKTO___TEXT___")
{
mReceivedFiles->append(name);
mReceivingText = true;
mTextToReceive.clear();
mCurrentFile = NULL;
}
// Altrimenti creo il nuovo file
else
{
// Se il file è in una cartella rinominata, devo provvedere di conseguenza
if ((name.indexOf('/') != -1) && (name.section("/", 0, 0) == mRootFolderName))
name = name.replace(0, name.indexOf('/'), mRootFolderRenamed);
// Se il file esiste già cambio il nome di quello nuovo
int i = 2;
QString originalName = name;
while (QFile::exists(name)) {
QFileInfo fi(originalName);
name = fi.baseName() + " (" + QString::number(i) + ")." + fi.completeSuffix();
i++;
}
mReceivedFiles->append(name);
mCurrentFile = new QFile(name);
bool ret = mCurrentFile->open(QIODevice::WriteOnly);
if (!ret)
{
emit receiveFileCancelled();
// Chiusura socket
if (mCurrentSocket)
{
mCurrentSocket->disconnect();
mCurrentSocket->disconnectFromHost();
mCurrentSocket->close();
mCurrentSocket->deleteLater();
mCurrentSocket = NULL;
}
// Rilascio memoria
delete mReceivedFiles;
mReceivedFiles = NULL;
// Impostazione stato
mIsReceiving = false;
return;
}
mReceivingText = false;
}
mRecvStatus = DATA;
break;
}
case DATA:
{
// Provo a leggere quanto mi serve per finire il file corrente
// (o per svuotare il buffer dei dati ricevuti)
qint64 s = (mCurrentSocket->bytesAvailable() > (mElementSize - mElementReceivedData))
? (mElementSize - mElementReceivedData)
: mCurrentSocket->bytesAvailable();
QByteArray d = mCurrentSocket->read(s);
mElementReceivedData += d.size();
mTotalReceivedData += d.size();
updateStatus();
// Salvo i dati letti
if (!mReceivingText)
mCurrentFile->write(d);
else
mTextToReceive.append(d);
// Verifico se ho completato l'elemento corrente
if (mElementReceivedData == mElementSize)
{
// Completato, chiudo il file e mi preparo per il prossimo elemento
mElementSize = -1;
if (!mReceivingText)
{
mCurrentFile->deleteLater();
mCurrentFile = NULL;
}
mRecvStatus = FILENAME;
}
break;
}
}
}
}
void DuktoProtocol::closedConnectionTmp()
{
QTimer::singleShot(500, this, SLOT(closedConnection()));
}
// Chiusura della connessione TCP in ricezione
void DuktoProtocol::closedConnection()
{
// empty the receive buffer
readNewData();
// Closing any current file
if (mCurrentFile)
{
QString name;
name = mCurrentFile->fileName();
mCurrentFile->close();
delete mCurrentFile;
mCurrentFile = NULL;
QFile::remove(name);
receiveFileCancelled();
}
else if (!mReceivingText) // Receiving file ended
{
receiveFileComplete(mReceivedFiles, mTotalSize);
// TODO: notify for recieving file
}
else // Receiving text ended
{
QString rec = QString::fromUtf8(mTextToReceive);
receiveTextComplete(&rec, mTotalSize);
// TODO: notify for recieving text
}
// closing socket
if (mCurrentSocket)
{
mCurrentSocket->disconnect();
mCurrentSocket->disconnectFromHost();
mCurrentSocket->close();
mCurrentSocket->deleteLater();
mCurrentSocket = NULL;
}
// release memory
delete mReceivedFiles;
mReceivedFiles = NULL;
// reset status
mIsReceiving = false;
}
void DuktoProtocol::sendFile(QString ipDest, qint16 port, QStringList files)
{
// Check for default port
if (port == 0) port = DEFAULT_TCP_PORT;
// Verifica altre attività in corso
if (mIsReceiving || mIsSending) return;
mIsSending = true;
// File da inviare
mFilesToSend = expandTree(files);
mFileCounter = 0;
// Connessione al destinatario
mCurrentSocket = new QTcpSocket(this);
// Gestione segnali
connect(mCurrentSocket, SIGNAL(connected()), this, SLOT(sendMetaData()), Qt::DirectConnection);
connect(mCurrentSocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(sendConnectError(QAbstractSocket::SocketError)), Qt::DirectConnection);
connect(mCurrentSocket, SIGNAL(bytesWritten(qint64)), this, SLOT(sendData(qint64)), Qt::DirectConnection);
// Connessione
mCurrentSocket->connectToHost(ipDest, port);
}
void DuktoProtocol::sendText(QString ipDest, qint16 port, QString text)
{
// Check for default port
if (port == 0) port = DEFAULT_TCP_PORT;
// Verifica altre attività in corso
if (mIsReceiving || mIsSending) return;
mIsSending = true;
// Testo da inviare
mFilesToSend.clear();
mFilesToSend.append("___DUKTO___TEXT___");
mFileCounter = 0;
mTextToSend = text;
// Connessione al destinatario
mCurrentSocket = new QTcpSocket(this);
connect(mCurrentSocket, SIGNAL(connected()), this, SLOT(sendMetaData()), Qt::DirectConnection);
connect(mCurrentSocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(sendConnectError(QAbstractSocket::SocketError)), Qt::DirectConnection);
connect(mCurrentSocket, SIGNAL(bytesWritten(qint64)), this, SLOT(sendData(qint64)), Qt::DirectConnection);
mCurrentSocket->connectToHost(ipDest, port);
}
void DuktoProtocol::sendScreen(QString ipDest, qint16 port, QString path)
{
// Check for default port
if (port == 0) port = DEFAULT_TCP_PORT;
// Verifica altre attività in corso
if (mIsReceiving || mIsSending) return;
mIsSending = true;
// File da inviare
QStringList files;
files.append(path);
mFilesToSend = expandTree(files);
mFileCounter = 0;
mSendingScreen = true;
// Connessione al destinatario
mCurrentSocket = new QTcpSocket(this);
// Gestione segnali
connect(mCurrentSocket, SIGNAL(connected()), this, SLOT(sendMetaData()), Qt::DirectConnection);
connect(mCurrentSocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(sendConnectError(QAbstractSocket::SocketError)), Qt::DirectConnection);
connect(mCurrentSocket, SIGNAL(bytesWritten(qint64)), this, SLOT(sendData(qint64)), Qt::DirectConnection);
// Connessione
mCurrentSocket->connectToHost(ipDest, port);
}
void DuktoProtocol::sendMetaData()
{
// Impostazione buffer di invio
#if defined(Q_OS_WIN)
int v = 49152;
::setsockopt(mCurrentSocket->socketDescriptor(), SOL_SOCKET, SO_SNDBUF, (char*)&v, sizeof(v));
#endif
// Header
// - N. entità (file, cartelle, ecc...)
// - Dimensione totale
// - Nome primo file
// - Dimensione primo (e unico) file (-1 per una cartella)
QByteArray header;
qint64 tmp;
// N. entità
tmp = mFilesToSend.count();
header.append((char*) &tmp, sizeof(tmp));
// Dimensione totale
mTotalSize = computeTotalSize(mFilesToSend);
header.append((char*) &mTotalSize, sizeof(mTotalSize));
// Primo elemento
header.append(nextElementHeader());
// Invio header
mCurrentSocket->write(header);
// Inizializzazione variabili
mTotalSize += header.size();
mSentData = 0;
mSentBuffer = 0;
// Aggiornamento interfaccia utente
updateStatus();
}
void DuktoProtocol::sendData(qint64 b)
{
QByteArray d;
// Aggiornamento statistiche
mSentData += b;
updateStatus();
// Verifica se tutti i dati messi nel buffer
// sono stati inviati
mSentBuffer -= b;
// Se ci sono altri dati da inviare, attendo
// che vengano inviati
if (mSentBuffer > 0) return;
// Se si tratta di un invio testuale, butto dentro
// tutto il testo
if ((!mTextToSend.isEmpty()) && (mFilesToSend.at(mFileCounter - 1) == "___DUKTO___TEXT___"))
{
d.append(mTextToSend.toUtf8().data());
mCurrentSocket->write(d);
mSentBuffer = d.size();
mTextToSend.clear();
return;
}
// Se il file corrente non è ancora terminato
// invio una nuova parte del file
if (mCurrentFile)
d = mCurrentFile->read(10000);
if (d.size() > 0)
{
mCurrentSocket->write(d);
mSentBuffer = d.size();
return;
}
// Altrimenti chiudo il file e passo al prossimo
d.append(nextElementHeader());
// Non ci sono altri file da inviare?
if (d.size() == 0)
{
closeCurrentTransfer();
return;
}
// Invio l'header insime al primo chunk di file
mTotalSize += d.size();
if (mCurrentFile)
d.append(mCurrentFile->read(10000));
mCurrentSocket->write(d);
mSentBuffer += d.size();
return;
}
// Chiusura trasferimento dati
void DuktoProtocol::closeCurrentTransfer(bool aborted)
{
mCurrentSocket->disconnect();
mCurrentSocket->disconnectFromHost();
if (mCurrentSocket->state() != QTcpSocket::UnconnectedState)
mCurrentSocket->waitForDisconnected(1000);
mCurrentSocket->close();
mCurrentSocket->deleteLater();
mCurrentSocket = NULL;
if (mCurrentFile)
{
mCurrentFile->close();
delete mCurrentFile;
mCurrentFile = NULL;
}
mIsSending = false;
if (!aborted)
emit sendFileComplete();
mFilesToSend.clear();
}
// Aggiornamento delle statistiche di invio
void DuktoProtocol::updateStatus()
{
if (mIsSending)
emit transferStatusUpdate(mTotalSize, mSentData);
else if (mIsReceiving)
emit transferStatusUpdate(mTotalSize, mTotalReceivedData);
}
// In caso di errore di connessione
void DuktoProtocol::sendConnectError(QAbstractSocket::SocketError e)
{
if (mCurrentSocket)
{
mCurrentSocket->close();
mCurrentSocket->deleteLater();
mCurrentSocket = NULL;
}
if (mCurrentFile)
{
mCurrentFile->close();
delete mCurrentFile;
mCurrentFile = NULL;
}
mIsSending = false;
sendFileError(e);
}
// Dato un elenco di file e cartelle, viene espanso in modo da
// contenere tutti i file e le cartelle contenuti
QStringList DuktoProtocol::expandTree(const QStringList& files)
{
// Percorso base
QString bp = files.first();
if (bp.right(1) == "/") bp.chop(1);
mBasePath = QFileInfo(bp).absolutePath();
if (mBasePath.right(1) == "/") mBasePath.chop(1);
// Iterazione sugli elementi
QStringList expanded;
for(QStringList::const_iterator iter = files.constBegin(); iter != files.constEnd(); ++iter)
addRecursive(expanded, *iter);
return expanded;
}
// Aggiunge ricorsivamente tutte le cartelle e file contenuti in una cartella
void DuktoProtocol::addRecursive(QStringList& e, QString path)
{
path.replace("//", "/");
path.replace("\\", "/");
if (path.right(1) == "/") path.chop(1);
e.append(path);
QString tempPath = path + "/";
if (QFileInfo(path).isDir())
{
QStringList entries = QDir(path).entryList(QDir::AllEntries | QDir::Hidden | QDir::System | QDir::NoDotAndDotDot);
for(QStringList::const_iterator iter = entries.constBegin(); iter != entries.constEnd(); ++iter)
addRecursive(e, tempPath + *iter);
}
}
// Restituisce l'header da inviare per il prossimo elemento
// da tramsettere
QByteArray DuktoProtocol::nextElementHeader()
{
QByteArray header;
// Ricava il nome del file (se non è l'ultimo)
if (mFilesToSend.size() == mFileCounter) return header;
QString fullname = mFilesToSend.at(mFileCounter++);
// Chiusura file precedente, se non è già stato chiuso
if (mCurrentFile) {
mCurrentFile->close();
delete mCurrentFile;
mCurrentFile = NULL;
}
// Verifico se si tratta di un invio testo
if (fullname == "___DUKTO___TEXT___") {
header.append(fullname.toUtf8() + '\0');
qint64 size = mTextToSend.toUtf8().length();
header.append((char*) &size, sizeof(size));
return header;
}
// Nome elemento
QString name;
// Verifico se si tratta di un invio screen
if (mSendingScreen) {
name = "Screenshot.jpg";
mSendingScreen = false;
}
else
name = fullname;
// Aggiunta nome file all'header
name.replace(mBasePath + "/", "");
header.append(name.toUtf8() + '\0');
// Dimensione elemento
qint64 size = -1;
QFileInfo fi2(fullname);
if (fi2.isFile()) size = fi2.size();
header.append((char*) &size, sizeof(size));
// Apertura file
if (size > -1) {
mCurrentFile = new QFile(fullname);
mCurrentFile->open(QIODevice::ReadOnly);
}
return header;
}
// Calcola l'occupazione totale di tutti i file da trasferire
qint64 DuktoProtocol::computeTotalSize(const QStringList& e)
{
// Se è un invio testuale
if ((e.length() == 1) && (e.first() == "___DUKTO___TEXT___"))
return mTextToSend.toUtf8().length();
// Se è un invio normale
qint64 size = 0;
for(QStringList::const_iterator iter = e.constBegin(); iter != e.constEnd(); ++iter)
{
QFileInfo fi(*iter);
if (!fi.isDir())
size += fi.size();
}
return size;
}
// Invia un pacchetto a tutti gli indirizzi broadcast del PC
void DuktoProtocol::sendToAllBroadcast(const QByteArray& packet, const QList<qint16>& ports)
{
// Elenco interfacce disponibili
QList<QNetworkInterface> ifaces = QNetworkInterface::allInterfaces();
// Iterazione sulle interfacce
for(QList<QNetworkInterface>::const_iterator iface = ifaces.constBegin(); iface != ifaces.constEnd(); ++iface)
{
// Iterazione per tutti gli IP dell'interfaccia
QList<QNetworkAddressEntry> addrs = iface->addressEntries();
// Invio pacchetto per ogni IP di broadcast
for(QList<QNetworkAddressEntry>::const_iterator addr = addrs.constBegin(); addr != addrs.constEnd(); ++addr)
if ((addr->ip().protocol() == QAbstractSocket::IPv4Protocol) && !addr->broadcast().toString().isEmpty())
{
for(QList<qint16>::const_iterator port = ports.constBegin(); port != ports.constEnd(); ++port)
{
mSocket->writeDatagram(packet.data(), packet.length(), addr->broadcast(), *port);
mSocket->flush();
}
}
}
}
// Interrompe un trasferimento in corso (utilizzabile solo lato invio)
void DuktoProtocol::abortCurrentTransfer()
{
// Check if it's sending data
if (!mIsSending) return;
// Abort current connection
closeCurrentTransfer(true);
emit sendFileAborted();
}
// Aggiorna il buddy name dell'utente locale
void DuktoProtocol::updateBuddyName()
{
// Invio pacchetto di disconnessione
sayGoodbye();
// Invio pacchetto di annuncio con il nuovo nome
sayHello(QHostAddress::Broadcast, true);
}