-
Notifications
You must be signed in to change notification settings - Fork 0
/
gorgzorg.cpp
1309 lines (1117 loc) · 37.4 KB
/
gorgzorg.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
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* This file is part of GorgZorg, a simple multiplatform CLI network file transfer tool.
* It was strongly inspired by the following article:
* https://topic.alibabacloud.com/a/file-transfer-using-the-tcp-protocol-in-qt-can-be-looped-in-one-direction_8_8_10249539.html
* Copyright (C) 2021 Alexandre Albuquerque Arnt
*
* 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.
*
* Source code hosted on: https://github.com/aarnt/gorgzorg
*/
#include "gorgzorg.h"
#include <iostream>
#ifndef Q_OS_WIN
#include <sys/ioctl.h>
#include <termios.h>
#else
#include <conio.h>
#endif
#include <QDataStream>
#include <QTcpSocket>
#include <QTcpServer>
#include <QHostAddress>
#include <QFile>
#include <QTextStream>
#include <QProcess>
#include <QDirIterator>
#include <QEventLoop>
#include <QNetworkInterface>
#include <QTime>
#include <QRegularExpression>
#include <QElapsedTimer>
/*
* Sleeps given ms miliseconds
*/
/*void qSleep(int ms)
{
#ifdef Q_OS_WIN
Sleep(uint(ms));
#else
struct timespec ts = { ms / 1000, (ms % 1000) * 1000 * 1000 };
nanosleep(&ts, NULL);
#endif
}*/
#ifndef Q_OS_WIN
/*
* Retrieves a char from stdin, with no need for an ENTER
*/
int readCharResponse()
{
static bool initflag = false;
static const int STDIN = 0;
if (!initflag) {
// Use termios to turn off line buffering
struct termios term;
tcgetattr(STDIN, &term);
term.c_lflag &= ~ICANON;
tcsetattr(STDIN, TCSANOW, &term);
setbuf(stdin, NULL);
initflag = true;
}
int nbbytes;
ioctl(STDIN, FIONREAD, &nbbytes); // 0 is STDIN
return nbbytes;
}
#endif
/*
* Asks user about strQuestion. The reply will be just 1 char size
*/
char question(const QString &strQuestion)
{
QTextStream(stdout) << strQuestion;
#ifndef Q_OS_WIN
while (!readCharResponse())
{
fflush(stdout);
}
return (getchar());
#else
while (!_kbhit())
{
fflush(stdout);
}
return _getch();
#endif
}
/*
* GorgZorg class methods
*/
QString GorgZorg::getWorkingDirectory()
{
QString res;
QProcess pwd;
QStringList params;
#ifndef Q_OS_WIN
pwd.start(QLatin1String("pwd"), params);
#else
pwd.start(QLatin1String("cd"), params);
#endif
pwd.waitForFinished(-1);
res = pwd.readAllStandardOutput();
res.remove("\n");
return res;
}
GorgZorg::GorgZorg()
{
m_tcpClient = new QTcpSocket (this);
m_sendTimes = 0;
m_totalSent = 0;
m_targetAddress = "";
m_block = ctn_BLOCK_SIZE;
m_port = 10000;
m_elapsedTime = new QElapsedTimer();
m_alwaysAccept = false;
m_askForAccept = true;
m_singleTransfer = false;
m_tarContents = false;
m_zipContents = false;
m_verbose = false;
m_quitServer = false;
QObject::connect(m_tcpClient, &QTcpSocket::readyRead, this, &GorgZorg::readResponse);
}
/*
* Whenever a reply from the server comes
*/
void GorgZorg::readResponse()
{
//What did we receive from the server?
QString ret = m_tcpClient->readAll();
//std::cout << "Received response: " << ret.toLatin1().data() << std::endl;
if (ret == ctn_ZORGED_OK)
{
std::cout << "Zorged OK received" << std::endl;
emit endTransfer();
}
else if (ret == ctn_ZORGED_OK_SEND)
{
std::cout << "Zorged OK SEND received" << std::endl;
emit okSend();
}
else if (ret == ctn_ZORGED_OK_SEND_AND_ZORGED_OK) //The two previous msgs may arrive truncated!
{
emit okSend();
emit endTransfer();
std::cout << "Zorged OK SEND received" << std::endl;
std::cout << "Zorged OK received" << std::endl;
}
else if (ret == ctn_ZORGED_CANCEL_SEND)
{
removeArchive();
std::cout << "Zorged CANCEL received. Aborting send!" << std::endl;
exit(0);
}
}
/*
* Returns true if IPv4 octects are well formed
*/
bool GorgZorg::isValidIP(const QString &ip)
{
bool res = false;
if (ip == "0.0.0.0" || ip == "255.255.255.255")
return res;
QRegularExpression re("^(\\d+).(\\d+).(\\d+).(\\d+)$");
QRegularExpressionMatch rem = re.match(ip);
if (rem.hasMatch())
{
bool ok;
int oc1 = rem.captured(1).toInt(&ok);
int oc2 = rem.captured(2).toInt(&ok);
int oc3 = rem.captured(3).toInt(&ok);
int oc4 = rem.captured(4).toInt(&ok);
if ((oc1 >= 0 && oc1 <= 255) && (oc2 >= 0 && oc2 <= 255) &&
(oc3 >= 0 && oc3 <= 255) && (oc4 >= 0 && oc4 <= 255))
res = true;
}
return res;
}
/*
* Test if both client and server are running on a private IPv4 network
*/
bool GorgZorg::isLocalIP(const QString &ip)
{
if (ip.startsWith("10.0") || ip.startsWith("127.0.0") ||
ip.startsWith("172.16") || ip.startsWith("192.168"))
return true;
else
return false;
}
/*
* Returns the SHELL environment variable, if not set defaults to sh.
*/
QString GorgZorg::getShell()
{
QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
QString shell = env.value(QStringLiteral("SHELL"), QStringLiteral("/bin/sh"));
return shell;
}
/*
* Creates a ".tar" or ".tar.gz" archive to send based on "-tar"/"-zip" command line params
*/
QString GorgZorg::createArchive(const QString &pathToArchive)
{
bool asterisk = false;
QString realPath;
QString filter;
if (pathToArchive.contains(QRegularExpression("\\*\\.*")))
{
asterisk = true;
int cutName=pathToArchive.size()-pathToArchive.lastIndexOf(QDir::separator())-1;
filter = pathToArchive.right(cutName);
realPath = pathToArchive.left(pathToArchive.size()-cutName);
}
if (m_zipContents)
std::cout << std::endl << "Compressing " << pathToArchive.toLatin1().data();
else
std::cout << std::endl << "Archiving " << pathToArchive.toLatin1().data();
QTime time = QTime::currentTime();
QString random = QString::number(time.hour()) +
QString::number(time.minute()) +
QString::number(time.second()) +
QString::number(time.msec());
QString archiveFileName = QString("gorged_%1").arg(random);
QProcess p;
QStringList tarParams;
if (m_zipContents)
tarParams << QLatin1String("-czf");
else
tarParams << QLatin1String("-cf");
if (asterisk)
{
#ifndef Q_OS_WIN
if (m_zipContents)
{
archiveFileName += QLatin1String(".tar.gz");
}
else
{
archiveFileName += QLatin1String(".tar");
}
QStringList findParams;
QString findCommand = QLatin1String("find ") + realPath +
QLatin1String(" -name ") + QLatin1String("\"") + filter + QLatin1String("\"") +
QLatin1String(" -exec tar ") + tarParams.at(0) + QLatin1String(" ") + archiveFileName + QLatin1String(" {} +");
findParams << QLatin1String("-c");
findParams << findCommand;
p.execute(getShell(), findParams);
p.waitForFinished(-1);
p.close();
#else
realPath.remove(QChar('\''));
filter.remove(QChar('\''));
QString compressionLevel;
if (m_zipContents)
{
compressionLevel = "-mx1";
}
else
{
compressionLevel = "-mx0";
}
archiveFileName += QLatin1String(".7z");
//Get-ChildItem c:\temp\*.dll -Recurse | Compress-Archive -Update -CompressionLevel NoCompression -DestinationPath c:\temp\power.zip
/*QString params = "powershell.exe -Command \"Get-ChildItem " + realPath + filter +
" -Recurse | Compress-Archive -Update -CompressionLevel " + compressionLevel +
" -DestinationPath .\\" + archiveFileName + "\"";*/
//qout << Qt::endl << QLatin1String("powershell command: %1").arg(params) << Qt::endl;
//qout << Qt::endl << QLatin1String("powershell output: %1").arg(p.readAllStandardOutput()) << Qt::endl;
//First, let's find where 7zip is located
QStringList wp;
wp << "/R" << "\\Program Files" << "7z.exe";
p.start("where", wp);
p.waitForFinished(-1);
QString pathTo7zip = p.readAllStandardOutput();
pathTo7zip.remove("\r\n");
//qout << Qt::endl << QLatin1String("where output: %1").arg(pathTo7zip);
if (!pathTo7zip.contains("7z.exe"))
{
wp << "/R" << "\\Program Files (x86)" << "7z.exe";
p.start("where", wp);
p.waitForFinished(-1);
pathTo7zip = p.readAllStandardOutput();
pathTo7zip.remove("\r\n");
//qout << Qt::endl << QLatin1String("where output: %1").arg(pathTo7zip);
}
if (pathTo7zip.contains("7z.exe"))
{
//"c:\Program Files\7-Zip\7z.exe" a c:\temp\test10.7zip c:\Qt\6.0.1\*.dll -r -mx1
QString params = "\"" + pathTo7zip + "\" a " + archiveFileName + " " + realPath + filter + " -r " + compressionLevel;
p.start(params);
p.waitForFinished(-1);
p.close();
}
#endif
}
else
{
if (m_zipContents)
{
archiveFileName += QLatin1String(".tar.gz");
}
else
{
archiveFileName += QLatin1String(".tar");
}
tarParams << archiveFileName;
tarParams << pathToArchive;
p.execute(QLatin1String("tar"), tarParams);
p.waitForFinished(-1);
p.close();
}
return archiveFileName;
}
/*
* Removes any not sent archive
*/
void GorgZorg::removeArchive()
{
if (!m_archiveFileName.isEmpty() && QFile::exists(m_archiveFileName) &&
(m_archiveFileName.endsWith(".tar") || m_archiveFileName.endsWith(".tar.gz") ||
m_archiveFileName.endsWith(".7z")))
{
QFile::remove(m_archiveFileName);
}
}
/*
* Opens the given file. If it cannot open, returns false
*/
bool GorgZorg::prepareToSendFile(const QString &fName)
{
m_fileName = fName;
m_loadSize = 0;
m_byteToWrite = 0;
m_totalSize = 0;
m_outBlock.clear();
m_sendingADir = false;
if (fName.startsWith(ctn_DIR_ESCAPE))
{
m_sendingADir = true;
}
else
{
m_localFile = new QFile(m_fileName);
if (!m_localFile->open(QFile::ReadOnly))
{
std::cout << std::endl << "ERROR: " << m_fileName.toLatin1().data() << " could not be opened" << std::endl;
return false;
}
}
return true;
}
/*
* Transfers a single file when traversing a directory passed by command line
*/
void GorgZorg::sendFile(const QString &filePath)
{
if (prepareToSendFile(filePath))
{
if (m_sendTimes == 0) // Only the first time it is sent, it happens when the connection generates the signal connect
{
m_tcpClient->connectToHost(QHostAddress(m_targetAddress), m_port);
m_sendTimes = 1;
}
else
{
send(); // When sending for the first time, connectToHost initiates the connect signal to call send, and you need to call send after the second time
}
}
else return;
QEventLoop eventLoop;
QObject::connect(this, &GorgZorg::endTransfer, &eventLoop, &QEventLoop::quit);
eventLoop.exec();
}
/*
* Threaded methods to connect and send data to client
*
* It can send just one file or entire paths (with subpaths)
* When sending paths, it can archive them with tar/gzip before sending
*
* connectAndSend is the main method called directly by the "-g" command line param
*/
void GorgZorg::connectAndSend(const QString &targetAddress, const QString &pathToGorg)
{
m_targetAddress = targetAddress;
QFileInfo fi(pathToGorg);
bool asterisk = false;
QString realPath;
QString filter;
if (pathToGorg.contains(QRegularExpression("\\*\\.*")))
{
asterisk = true;
int cutName=pathToGorg.size()-pathToGorg.lastIndexOf(QDir::separator())-1;
filter = pathToGorg.right(cutName);
realPath = pathToGorg.left(pathToGorg.size()-cutName);
#ifdef Q_OS_WIN
filter.remove(QChar('\''));
realPath.remove(QChar('\''));
#endif
//qout << Qt::endl << QLatin1String("Filter: %1").arg(filter) << Qt::endl;
//qout << Qt::endl << QLatin1String("Real Path: %1").arg(realPath) << Qt::endl;
if (realPath.isEmpty())
realPath = getWorkingDirectory();
}
if (!asterisk && !fi.exists())
{
std::cout << std::endl << "ERROR: " << pathToGorg.toLatin1().data() << " could not be found!" << std::endl;
exit(1);
}
if (!asterisk && fi.isFile())
{
if (m_tarContents || m_zipContents)
{
m_archiveFileName = createArchive(pathToGorg);
if (m_verbose) m_elapsedTime->start();
sendFileHeader(m_archiveFileName);
}
else
{
if (m_verbose) m_elapsedTime->start();
sendFileHeader(pathToGorg);
}
}
else
{
if (m_tarContents || m_zipContents)
{
{
m_archiveFileName = createArchive(pathToGorg);
if (m_verbose) m_elapsedTime->start();
sendFileHeader(m_archiveFileName);
}
}
else
{
if (m_verbose) m_elapsedTime->start();
if (asterisk)
sendDirHeader(realPath);
else
sendDirHeader(pathToGorg);
QDirIterator *it;
//Loop thru the dirs/files on pathToGorg
if (asterisk) //If user passed some name filter path (ex: *.mp3)
{
QStringList nameFilters;
nameFilters << filter;
it = new QDirIterator(realPath, nameFilters, QDir::AllEntries | QDir::Hidden | QDir::System, QDirIterator::Subdirectories);
}
else
it = new QDirIterator(pathToGorg, QDir::AllEntries | QDir::Hidden | QDir::System, QDirIterator::Subdirectories);
while (it->hasNext())
{
QString traverse = it->next();
if (traverse.endsWith(QLatin1String(".")) || traverse.endsWith(QLatin1String(".."))) continue;
if (it->fileInfo().isDir())
traverse = ctn_DIR_ESCAPE + traverse;
sendFile(traverse);
}
}
}
sendEndOfTransfer();
//Let's print some statistics if verbose is on
if (m_verbose)
{
double duration = m_elapsedTime->elapsed() / 1000.0; //duration of send in seconds
double bytesSent = (m_totalSent / 1024.0) / 1024.0; //sent bytes in MB
double speed = bytesSent / duration;
QString strDuration = QString::number(duration, 'f', 2);
QString strBytesSent = QString::number(bytesSent, 'f', 2);
QString strSpeed = QString::number(speed, 'f', 2);
std::cout << std::endl << "Time elapsed: " << strDuration.toLatin1().data() << "s" << std::endl;
std::cout << "Bytes sent: " << strBytesSent.toLatin1().data() << " MB" << std::endl;
std::cout << "Speed: " << strSpeed.toLatin1().data() << " MB/s" << std::endl;
}
removeArchive();
std::cout << std::endl;
exit(0);
}
/*
* Sends END OF TRANSFER signal to the server (goodbye, cruel world!)
*/
void GorgZorg::sendEndOfTransfer()
{
QObject::disconnect(m_tcpClient, &QTcpSocket::bytesWritten, this, &GorgZorg::goOnSend);
//Tests if client is connected before going on
if (m_tcpClient->state() == QAbstractSocket::UnconnectedState)
{
return;
}
m_loadSize = m_block * 1024; // The size of data sent each time
m_byteToWrite = 0;
m_totalSize = 0;
m_totalSent += m_totalSize;
QDataStream out(&m_outBlock, QIODevice::WriteOnly);
m_currentFileName = ctn_END_OF_TRANSFER;
std::cout << std::endl << "Gorging goodbye..." << std::endl;
out << qint64(0) << qint64(0) << m_currentFileName << true;
m_totalSize += m_outBlock.size(); // The total size is the file size plus the size of the file name and other information
m_byteToWrite += m_outBlock.size();
m_totalSent += m_outBlock.size();
out.device()->seek(0); // Go back to the beginning of the byte stream to write a qint64 in front, which is the total size and file name and other information size
out << m_totalSize << qint64(m_outBlock.size());
m_tcpClient->write(m_outBlock); // Send the read file to the socket
m_tcpClient->waitForBytesWritten(-1);
}
/*
* Send file header information, so the server can opt to accept or deny transfer
*/
void GorgZorg::sendFileHeader(const QString &filePath)
{
if (prepareToSendFile(filePath))
{
m_tcpClient->connectToHost(QHostAddress(m_targetAddress), m_port);
m_tcpClient->waitForConnected(-1);
if (m_tcpClient->state() == QAbstractSocket::UnconnectedState)
{
std::cout << std::endl << "ERROR: It seems there is no one zorging on " <<
m_targetAddress.toLatin1().data() << ":" << QString::number(m_port).toLatin1().data() << std::endl;
removeArchive();
exit(1);
}
m_loadSize = m_block * 1024; // The size of data sent each time
if (m_sendingADir)
{
m_byteToWrite = 0;
m_totalSize = 0;
}
else
{
m_byteToWrite = m_localFile->size(); //The size of the remaining data
m_totalSize = m_localFile->size();
m_totalSent += m_totalSize;
}
QDataStream out(&m_outBlock, QIODevice::WriteOnly);
m_currentFileName = m_fileName;
if (m_sendingADir)
{
QString aux = QString("Gorging header of dir %1").arg(m_currentFileName);
std::cout << std::endl << aux.remove(ctn_DIR_ESCAPE).toLatin1().data() << std::endl;
}
else
{
std::cout << std::endl << "Gorging header of " << m_currentFileName.toLatin1().data() << std::endl;
}
out << qint64(0) << qint64(0) << m_currentFileName << false;
m_totalSize += m_outBlock.size(); // The total size is the file size plus the size of the file name and other information
m_byteToWrite += m_outBlock.size();
m_totalSent += m_outBlock.size();
out.device()->seek(0); // Go back to the beginning of the byte stream to write a qint64 in front, which is the total size and file name and other information size
out << m_totalSize << qint64(m_outBlock.size());
m_tcpClient->write(m_outBlock); // Send the read file to the socket
m_tcpClient->waitForBytesWritten(-1);
QObject::connect(m_tcpClient, &QTcpSocket::bytesWritten, this, &GorgZorg::goOnSend);
//Wait until server accepts the sending...
QEventLoop eventLoop;
QObject::connect(this, &GorgZorg::okSend, &eventLoop, &QEventLoop::quit);
eventLoop.exec();
m_outBlock.clear();
m_totalSent = 0;
sendFileBody();
QObject::disconnect(this, &GorgZorg::okSend, &eventLoop, &QEventLoop::quit);
QObject::connect(this, &GorgZorg::endTransfer, &eventLoop, &QEventLoop::quit);
eventLoop.exec();
}
}
/*
* Sends directory header information, so the server can opt to accept or deny transfer
*/
void GorgZorg::sendDirHeader(const QString &filePath)
{
m_fileName = filePath;
m_outBlock.clear();
m_sendingADir = true;
m_localFile = new QFile(m_fileName);
m_tcpClient->connectToHost(QHostAddress(m_targetAddress), m_port);
m_tcpClient->waitForConnected(-1);
if (m_tcpClient->state() == QAbstractSocket::UnconnectedState)
{
std::cout << std::endl << "ERROR: It seems there is no one zorging on " <<
m_targetAddress.toLatin1().data() << ":" << QString::number(m_port).toLatin1().data() << std::endl;
removeArchive();
exit(1);
}
m_loadSize = m_block * 1024; // The size of data sent each time
m_byteToWrite = 0;
m_totalSize = 0;
QDataStream out(&m_outBlock, QIODevice::WriteOnly);
m_currentFileName = m_fileName;
QString aux = QString("Gorging header of dir %1").arg(m_currentFileName);
std::cout << std::endl << aux.remove(ctn_DIR_ESCAPE).toLatin1().data() << std::endl;
/* This is the beggining of a directory traverse send, so let's put 'false' in the last value (m_singleTransfer)
of the header so GorgZorg can read it as "This is not a single transfer!" */
out << qint64 (0) << qint64 (0) << m_currentFileName + QDir::separator() + QLatin1String(".") << false;
m_totalSize += m_outBlock.size(); // The total size is the file size plus the size of the file name and other information
m_byteToWrite += m_outBlock.size();
m_totalSent += m_outBlock.size();
out.device()->seek(0); // Go back to the beginning of the byte stream to write a qint64 in front, which is the total size and file name and other information size
out << m_totalSize << qint64(m_outBlock.size());
m_tcpClient->write(m_outBlock); // Send the read file to the socket
m_tcpClient->waitForBytesWritten(-1);
QEventLoop eventLoop;
QObject::connect(this, &GorgZorg::cancelSend, &eventLoop, &QEventLoop::quit);
QObject::connect(this, &GorgZorg::okSend, &eventLoop, &QEventLoop::quit);
eventLoop.exec();
m_outBlock.clear();
m_totalSent = 0;
m_sendTimes = 1;
delete m_localFile;
QObject::connect(this, &GorgZorg::endTransfer, &eventLoop, &QEventLoop::quit);
eventLoop.exec();
QObject::connect(m_tcpClient, &QTcpSocket::bytesWritten, this, &GorgZorg::goOnSend);
}
/*
* Sends file contents (called by sendFileHeader). It starts the real file sending...
*/
void GorgZorg::sendFileBody()
{
m_loadSize = m_block * 1024; // The size of data sent each time
if (m_sendingADir)
{
m_byteToWrite = 0;
m_totalSize = 0;
}
else
{
m_byteToWrite = m_localFile->size(); //The size of the remaining data
m_totalSize = m_localFile->size();
m_totalSent += m_totalSize;
}
QDataStream out(&m_outBlock, QIODevice::WriteOnly);
m_currentFileName = m_fileName;
if (m_sendingADir)
{
QString aux = QString("Gorging dir %1").arg(m_currentFileName);
std::cout << std::endl << aux.remove(ctn_DIR_ESCAPE).toLatin1().data() << std::endl;
}
else
{
std::cout << std::endl << "Gorging " << m_currentFileName.toLatin1().data() << std::endl;
}
m_byteToWrite += m_outBlock.size();
m_totalSent += m_outBlock.size();
m_outBlock = m_localFile->read(qMin(m_byteToWrite, m_loadSize));
m_tcpClient->write(m_outBlock); // Send the read file to the socket
}
/*
* Sends header information of the file that belongs to the path we are traversing
*/
void GorgZorg::send()
{
m_loadSize = m_block * 1024; // The size of data sent each time
if (m_sendingADir)
{
m_byteToWrite = 0;
m_totalSize = 0;
}
else
{
m_byteToWrite = m_localFile->size(); //The size of the remaining data
m_totalSize = m_localFile->size();
m_totalSent += m_totalSize;
}
QDataStream out(&m_outBlock, QIODevice::WriteOnly);
m_currentFileName = m_fileName;
if (m_sendingADir)
{
QString aux = QString("Gorging dir %1").arg(m_currentFileName);
std::cout << std::endl << aux.remove(ctn_DIR_ESCAPE).toLatin1().data() << std::endl;
}
else
{
std::cout << std::endl << "Gorging " << m_currentFileName.toLatin1().data() << std::endl;
}
out << qint64(0) << qint64(0) << m_currentFileName << true;
m_totalSize += m_outBlock.size(); // The total size is the file size plus the size of the file name and other information
m_byteToWrite += m_outBlock.size();
m_totalSent += m_outBlock.size();
out.device()->seek(0); // Go back to the beginning of the byte stream to write a qint64 in front, which is the total size and file name and other information size
out << m_totalSize << qint64(m_outBlock.size());
m_tcpClient->write(m_outBlock); // Send the read file to the socket
}
/*
* This is the slot that is called multiple times by all sending methods until the file is completly sent to the server
*/
void GorgZorg::goOnSend(qint64 numBytes) // Start sending file content
{
m_byteToWrite -= numBytes; // Remaining data size
if (m_sendingADir)
{
m_outBlock.resize(0);
m_tcpClient->write(m_outBlock);
}
else
{
m_outBlock = m_localFile->read(qMin(m_byteToWrite, m_loadSize));
m_tcpClient->write(m_outBlock);
}
//ui-> sendProgressBar->setMaximum(totalSize);
//ui-> sendProgressBar->setValue(totalSize-byteToWrite);
if (m_byteToWrite == 0) // Send completed
{
//QTextStream qout(stdout);
std::cout << "Gorging completed" << std::endl;
//If we gorged a tared file, let's remove it!
if (m_tarContents)
{
QString path = getWorkingDirectory();
path.remove(QLatin1Char('\n'));
path += QDir::separator() + m_currentFileName;
if (path.endsWith(".tar")) QFile::remove(path);
}
if (!m_sendingADir)
{
m_localFile->close();
}
}
}
/*
* SERVER SIDE PART *****************************************************************
*/
/*
* Starts listening for file transfers on port m_port of the given ipAddress
*/
void GorgZorg::startServer(const QString &ipAddress)
{
m_totalSize = 0;
m_byteReceived = 0;
m_server = new QTcpServer(this);
QString ip = ipAddress;
if (ip.isEmpty())
{
const QHostAddress &localhost = QHostAddress(QHostAddress::LocalHost);
for (auto &address: QNetworkInterface::allAddresses())
{
if (address.protocol() == QAbstractSocket::IPv4Protocol && address != localhost)
{
if (!isLocalIP(address.toString())) continue;
ip = address.toString();
}
}
}
if (ip.isEmpty())
{
std::cout << std::endl << "ERROR: No valid IP address could be found!" << std::endl;
exit(1);
}
if (!m_server->listen(QHostAddress(ip), m_port))
{
//If we could not bind to this port...
std::cout << "ERROR: " << ip.toLatin1().data() << " is unavailable or port " <<
QString::number(m_port).toLatin1().data() << " is already being used in this host!" << std::endl;
exit(1);
}
//Let's change the received files directory if the user especified one...
if (!m_zorgPath.isEmpty())
{
QDir::setCurrent(m_zorgPath);
}
QObject::connect(m_server, &QTcpServer::newConnection, this, &GorgZorg::acceptConnection);
std::cout << "Start zorging on " << ip.toLatin1().data() << ":" << QString::number(m_port).toLatin1().data() << "..." << std::endl;
}
void GorgZorg::acceptConnection()
{
std::cout << std::endl << "Connected, preparing to zorg files!" << std::endl;
m_receivedSocket = m_server->nextPendingConnection();
QObject::connect(m_receivedSocket, &QTcpSocket::readyRead, this, &GorgZorg::readClient);
}
/*
* Whenever clients send bytes, readClient is called!
*/
void GorgZorg::readClient()
{
if (m_byteReceived == 0) // just started to receive data, this data is file information
{
m_receivingADir = false;
m_createMasterDir = false;
//ui->receivedProgressBar->setValue(0);
QDataStream in(m_receivedSocket);
in >> m_totalSize >> m_byteReceived >> m_fileName >> m_singleTransfer;
if (m_fileName == ctn_END_OF_TRANSFER)
{
m_masterDir.clear();
m_byteReceived = 0;
m_totalSize = 0;
//Client is saying goodbye...
std::cout << std::endl << "See you next time!" << std::endl << std::endl;
if (m_quitServer)
exit(0);
else
return;
}
double totalSize;
QString strTotalSize;
if (!m_alwaysAccept)
{
if (m_singleTransfer == false && m_askForAccept == false)
{
m_askForAccept = true;
}
}
//Check if we have to replace directory separators
QChar here = QDir::separator();
int i=m_fileName.indexOf(here);
if (i == -1)
{
if (here == '/')
{
m_fileName.replace(QChar('\\'), QChar('/'));
}
else
{
m_fileName.replace(QChar('/'), QChar('\\'));
}
}
#ifdef Q_OS_WIN
if (m_fileName.startsWith(QDir::separator()))
{
m_fileName.remove(0, 1);
}
#endif
//qout << Qt::endl << QLatin1String("Received: %1").arg(m_fileName) << Qt::endl;
int cutName=m_fileName.size()-m_fileName.lastIndexOf(QDir::separator())-1;
m_currentFileName = m_fileName.right(cutName);
if (m_currentFileName == ".")
{
m_currentPath = m_fileName.remove(QString(QDir::separator())+QLatin1String("."));
m_currentFileName = m_currentPath;
m_createMasterDir = true;
}
else
{
m_currentPath = m_fileName.left(m_fileName.size()-cutName);
//qout << QLatin1String("First Path: %1").arg(m_currentPath) << Qt::endl;
}
if (!m_createMasterDir)
{
if (m_totalSize >= 1073741824)
{
totalSize = (m_totalSize / 1024.0) / 1024.0;
strTotalSize = QString::number(totalSize, 'f', 2) + " MB";
}
else
{
totalSize = m_totalSize / 1024.0;
strTotalSize = QString::number(totalSize, 'f', 2) + " KB";
}
}