/
QueueManager.cpp
3809 lines (3068 loc) · 105 KB
/
QueueManager.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
/*
* Copyright (C) 2001-2019 Jacek Sieka, arnetheduck on gmail point com
*
* 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 "stdinc.h"
#include "QueueManager.h"
#include "AirUtil.h"
#include "Bundle.h"
#include "ClientManager.h"
#include "ConnectionManager.h"
#include "DebugManager.h"
#include "DirectoryListing.h"
#include "DirectoryListingManager.h"
#include "Download.h"
#include "DownloadManager.h"
#include "ErrorCollector.h"
#include "FileReader.h"
#include "HashManager.h"
#include "LogManager.h"
#include "ResourceManager.h"
#include "ScopedFunctor.h"
#include "SearchManager.h"
#include "SearchResult.h"
#include "ShareManager.h"
#include "SimpleXMLReader.h"
#include "Transfer.h"
#include "UploadManager.h"
#include "UserConnection.h"
#include "ZUtils.h"
#include "version.h"
#include <boost/range/algorithm/copy.hpp>
#include <boost/range/algorithm/count_if.hpp>
#ifdef _WIN32
#include <mmsystem.h>
#include <limits>
#endif
#if !defined(_WIN32) && !defined(PATH_MAX) // Extra PATH_MAX check for Mac OS X
#include <sys/syslimits.h>
#endif
#ifdef ff
#undef ff
#endif
namespace dcpp {
using boost::range::for_each;
QueueManager::QueueManager() :
udp(Socket::TYPE_UDP),
tasks(true)
{
//add listeners in loadQueue
File::ensureDirectory(Util::getListPath());
File::ensureDirectory(Util::getBundlePath());
}
QueueManager::~QueueManager() {
}
void QueueManager::shutdown() noexcept {
SearchManager::getInstance()->removeListener(this);
TimerManager::getInstance()->removeListener(this);
ClientManager::getInstance()->removeListener(this);
ShareManager::getInstance()->removeListener(this);
if (SETTING(REMOVE_FINISHED_BUNDLES)){
WLock l(cs);
BundleList bl;
for (auto& b : bundleQueue.getBundles() | map_values) {
if (b->isCompleted()) {
bl.push_back(b);
}
}
for_each(bl.begin(), bl.end(), [=](BundlePtr& b) { bundleQueue.removeBundle(b); });
}
saveQueue(false);
if (!SETTING(KEEP_LISTS)) {
string path = Util::getListPath();
std::sort(protectedFileLists.begin(), protectedFileLists.end());
StringList filelists = File::findFiles(path, "*.xml.bz2", File::TYPE_FILE);
std::sort(filelists.begin(), filelists.end());
std::for_each(filelists.begin(), std::set_difference(filelists.begin(), filelists.end(),
protectedFileLists.begin(), protectedFileLists.end(), filelists.begin()), &File::deleteFile);
}
}
void QueueManager::recheckBundle(QueueToken aBundleToken) noexcept {
QueueItemList ql;
BundlePtr b;
{
RLock l(cs);
b = bundleQueue.findBundle(aBundleToken);
if (!b) {
return;
}
copy(b->getQueueItems().begin(), b->getQueueItems().end(), back_inserter(ql));
copy(b->getFinishedFiles().begin(), b->getFinishedFiles().end(), back_inserter(ql));
}
int64_t finishedSegmentsBegin = accumulate(ql.begin(), ql.end(), (int64_t)0, [&](int64_t old, const QueueItemPtr& qi) {
auto size = File::getSize(qi->getTarget());
if (size == -1) {
size = File::getSize(qi->getTempTarget());
}
return size > 0 ? old + size : old;
});
LogManager::getInstance()->message(STRING_F(INTEGRITY_CHECK_START_BUNDLE, b->getName() %
Util::formatBytes(finishedSegmentsBegin)), LogMessage::SEV_INFO);
// prepare for checking
auto oldPrio = b->getPriority();
auto oldStatus = b->getStatus();
setBundlePriority(b, Priority::PAUSED_FORCE);
Thread::sleep(1000);
setBundleStatus(b, Bundle::STATUS_RECHECK);
// check the files
int64_t failedBytes = 0;
QueueItemList failedItems;
for (auto& q : ql) {
if (recheckFileImpl(q->getTarget(), true, failedBytes)) {
failedItems.push_back(q);
}
}
// finish
LogManager::getInstance()->message(STRING_F(INTEGRITY_CHECK_FINISHED_BUNDLE, b->getName() %
Util::formatBytes(failedBytes)), LogMessage::SEV_INFO);
b->setStatus(oldStatus);
handleFailedRecheckItems(failedItems);
setBundlePriority(b, oldPrio);
}
void QueueManager::recheckFiles(QueueItemList aQL) noexcept {
LogManager::getInstance()->message(STRING_F(INTEGRITY_CHECK_START_FILES, aQL.size()), LogMessage::SEV_INFO);
QueueItemList failedItems;
int64_t failedBytes = 0;
for (auto& q : aQL) {
bool running;
{
RLock l(cs);
running = q->isRunning();
}
auto oldPrio = q->getPriority();
setQIPriority(q, Priority::PAUSED_FORCE);
if (running) {
Thread::sleep(1000);
}
if (recheckFileImpl(q->getTarget(), false, failedBytes)) {
failedItems.push_back(q);
}
setQIPriority(q, oldPrio);
}
handleFailedRecheckItems(failedItems);
LogManager::getInstance()->message(STRING_F(INTEGRITY_CHECK_FINISHED_FILES, Util::formatBytes(failedBytes)), LogMessage::SEV_INFO);
}
void QueueManager::handleFailedRecheckItems(const QueueItemList& ql) noexcept {
if (ql.empty())
return;
auto b = ql.front()->getBundle();
dcassert(b);
{
WLock l(cs);
for (auto q : ql) {
bundleQueue.removeBundleItem(q, false);
q->setStatus(QueueItem::STATUS_QUEUED);
q->setBundle(nullptr);
q->setTimeFinished(0);
bundleQueue.addBundleItem(q, b);
userQueue.addQI(q);
}
readdBundle(b);
}
fire(QueueManagerListener::BundleStatusChanged(), b);
}
bool QueueManager::recheckFileImpl(const string& aPath, bool isBundleCheck, int64_t& failedBytes_) noexcept{
QueueItemPtr q;
int64_t tempSize;
TTHValue tth;
string checkTarget;
auto failFile = [&](const string& aError) {
fire(QueueManagerListener::FileRecheckFailed(), q, aError);
LogManager::getInstance()->message(STRING_F(INTEGRITY_CHECK, aError % q->getTarget()), LogMessage::SEV_ERROR);
};
{
RLock l(cs);
q = fileQueue.findFile(aPath);
}
if (!q || q->isSet(QueueItem::FLAG_USER_LIST))
return false;
fire(QueueManagerListener::FileRecheckStarted(), q->getTarget());
{
RLock l(cs);
dcdebug("Rechecking %s\n", aPath.c_str());
// always check the final target in case of files added from other sources
checkTarget = Util::fileExists(q->getTarget()) ? q->getTarget() : q->getTempTarget();
tempSize = File::getSize(checkTarget);
if (tempSize == -1) {
if (q->getDownloadedBytes() > 0)
failFile(STRING(UNFINISHED_FILE_NOT_FOUND));
return false;
}
if (tempSize < Util::convertSize(64, Util::KB)) {
if (!isBundleCheck)
failFile(STRING(UNFINISHED_FILE_TOO_SMALL));
return false;
}
if (tempSize != q->getSize()) {
if (checkTarget == q->getTarget()) {
failFile(STRING(SIZE_MISMATCH));
return false;
}
try {
File(checkTarget, File::WRITE, File::OPEN).setSize(q->getSize());
} catch (const FileException& e) {
failFile(e.getError());
return false;
}
}
if (q->isRunning()) {
failFile(STRING(DOWNLOADS_RUNNING));
return false;
}
tth = q->getTTH();
}
TigerTree tt;
bool gotTree = HashManager::getInstance()->getTree(tth, tt);
QueueItem::SegmentSet done;
{
RLock l(cs);
// get q again in case it has been (re)moved
q = fileQueue.findFile(aPath);
if (!q)
return false;
if (!gotTree) {
failFile(STRING(NO_FULL_TREE));
return false;
}
//Clear segments
done = q->getDone();
q->resetDownloaded();
}
TigerTree ttFile(tt.getBlockSize());
DirSFVReader sfv(q->getFilePath());
auto fileCRC = sfv.hasFile(Text::toLower(q->getTargetFileName()));
CRC32Filter crc32;
try {
FileReader().read(checkTarget, [&](const void* x, size_t n) {
if (fileCRC)
crc32(x, n);
return ttFile.update(x, n), true;
});
} catch (const FileException & e) {
dcdebug("Error while reading file: %s\n", e.what());
failFile(e.getError());
return false;
}
{
RLock l(cs);
// get q again in case it has been (re)moved
q = fileQueue.findFile(aPath);
}
if (!q)
return false;
ttFile.finalize();
int64_t pos = 0, failedBytes = 0;
bool segmentsDone = false;
{
WLock l(cs);
boost::for_each(tt.getLeaves(), ttFile.getLeaves(), [&](const TTHValue& our, const TTHValue& file) {
// avoid going over the file size (would happen especially with finished items)
auto blockSegment = Segment(pos, min(q->getSize() - pos, tt.getBlockSize()));
if (our == file) {
q->addFinishedSegment(blockSegment);
} else {
// undownloaded segments aren't corrupted...
if (!blockSegment.inSet(done))
return;
dcdebug("Integrity check failed for the block at pos " I64_FMT "\n", pos);
failedBytes += tt.getBlockSize();
}
pos += tt.getBlockSize();
});
segmentsDone = q->segmentsDone();
}
if (failedBytes > 0) {
failedBytes_ += failedBytes;
LogManager::getInstance()->message(STRING_F(INTEGRITY_CHECK,
STRING_F(FILE_CORRUPTION_FOUND, Util::formatBytes(failedBytes)) % q->getTarget()),
LogMessage::SEV_WARNING);
} else if (fileCRC && ttFile.getRoot() == tth && *fileCRC != crc32.getValue()) {
LogManager::getInstance()->message(q->getTarget() + ": " + STRING(ERROR_HASHING_CRC32), LogMessage::SEV_ERROR);
}
if (ttFile.getRoot() == tth && !q->isDownloaded()) {
q->setTimeFinished(GET_TIME());
setFileStatus(q, QueueItem::STATUS_DOWNLOADED);
{
WLock l(cs);
userQueue.removeQI(q);
}
removeBundleItem(q, true);
//If no bad blocks then the file probably got stuck in the temp folder for some reason
if (checkTarget != q->getTarget()) {
renameDownloadedFile(q->getTempTarget(), q->getTarget(), q);
} else {
setFileStatus(q, QueueItem::STATUS_COMPLETED);
}
//failFile(STRING(FILE_ALREADY_FINISHED));
return false;
}
// we will also resume files that are added in the destination directory from other sources
if (!segmentsDone && (q->isDownloaded() || q->getTarget() == checkTarget)) {
try {
File::renameFile(q->getTarget(), q->getTempTarget());
} catch (const FileException& e) {
LogManager::getInstance()->message(STRING_F(UNABLE_TO_RENAME, q->getTarget() % e.getError()), LogMessage::SEV_ERROR);
}
}
if (q->isDownloaded() && !segmentsDone) {
return true;
}
fire(QueueManagerListener::FileRecheckDone(), q->getTarget());
fire(QueueManagerListener::ItemStatus(), q);
return false;
}
void QueueManager::getBloom(HashBloom& bloom) const noexcept {
RLock l(cs);
fileQueue.getBloom(bloom);
}
size_t QueueManager::getQueuedBundleFiles() const noexcept {
RLock l(cs);
return bundleQueue.getTotalFiles();
}
bool QueueManager::getSearchInfo(const string& aTarget, TTHValue& tth_, int64_t& size_) noexcept {
RLock l(cs);
QueueItemPtr qi = fileQueue.findFile(aTarget);
if(qi) {
tth_ = qi->getTTH();
size_ = qi->getSize();
return true;
}
return false;
}
struct PartsInfoReqParam{
PartsInfo parts;
string tth;
string myNick;
string hubIpPort;
string ip;
string udpPort;
};
void QueueManager::requestPartialSourceInfo(uint64_t aTick) noexcept {
BundlePtr bundle;
vector<const PartsInfoReqParam*> params;
{
RLock l(cs);
//find max 10 pfs sources to exchange parts
//the source basis interval is 5 minutes
FileQueue::PFSSourceList sl;
fileQueue.findPFSSources(sl);
for (auto& i : sl) {
auto source = i.first->getPartialSource();
const QueueItemPtr qi = i.second;
PartsInfoReqParam* param = new PartsInfoReqParam;
qi->getPartialInfo(param->parts, qi->getBlockSize());
param->tth = qi->getTTH().toBase32();
param->ip = source->getIp();
param->udpPort = source->getUdpPort();
param->myNick = source->getMyNick();
param->hubIpPort = source->getHubIpPort();
params.push_back(param);
source->setPendingQueryCount((uint8_t)(source->getPendingQueryCount() + 1));
source->setNextQueryTime(aTick + 300000); // 5 minutes
}
}
// Request parts info from partial file sharing sources
for (auto& param : params) {
//dcassert(param->udpPort > 0);
try {
AdcCommand cmd = SearchManager::getInstance()->toPSR(true, param->myNick, param->hubIpPort, param->tth, param->parts);
COMMAND_DEBUG(cmd.toString(), DebugManager::TYPE_CLIENT_UDP, DebugManager::OUTGOING, param->ip);
udp.writeTo(param->ip, param->udpPort, cmd.toString(ClientManager::getInstance()->getMyCID()));
} catch (...) {
dcdebug("Partial search caught error\n");
}
delete param;
}
}
DirectoryContentInfo QueueManager::getBundleContent(const BundlePtr& aBundle) const noexcept {
RLock l(cs);
auto files = aBundle->getQueueItems().size() + aBundle->getFinishedFiles().size();
auto directories = aBundle->isFileBundle() ? 0 : bundleQueue.getDirectoryCount(aBundle) - 1;
return DirectoryContentInfo(directories, files);
}
bool QueueManager::hasDownloadedBytes(const string& aTarget) {
RLock l(cs);
auto q = fileQueue.findFile(aTarget);
if (!q) {
throw QueueException(STRING(TARGET_REMOVED));
}
return q->getDownloadedBytes() > 0;
}
QueueItemPtr QueueManager::addList(const HintedUser& aUser, Flags::MaskType aFlags, const string& aInitialDir /* = ADC_ROOT */, const BundlePtr& aBundle /*nullptr*/) {
if (!Util::isAdcPath(aInitialDir)) {
throw QueueException(STRING_F(INVALID_PATH, aInitialDir));
}
// Pre-checks
checkSource(aUser);
if (aUser.hint.empty()) {
throw QueueException(STRING(HUB_UNKNOWN));
}
// Format the target
auto target = getListPath(aUser);
if((aFlags & QueueItem::FLAG_PARTIAL_LIST)) {
target += ".partial[" + Util::validateFileName(aInitialDir) + "]";
}
// Add in queue
QueueItemPtr q = nullptr;
{
WLock l(cs);
auto ret = fileQueue.add(target, -1, (Flags::MaskType)(QueueItem::FLAG_USER_LIST | aFlags), Priority::HIGHEST, aInitialDir, GET_TIME(), TTHValue());
if (!ret.second) {
//exists already
throw DupeException(STRING(LIST_ALREADY_QUEUED));
}
q = std::move(ret.first);
addSource(q, aUser, QueueItem::Source::FLAG_MASK, false);
if (aBundle) {
matchLists.insert(TokenStringMultiBiMap::value_type(aBundle->getToken(), q->getTarget()));
}
}
fire(QueueManagerListener::ItemAdded(), q);
//connect
if (aUser.user->isOnline()) {
ConnectionManager::getInstance()->getDownloadConnection(aUser, (aFlags & QueueItem::FLAG_PARTIAL_LIST) || (aFlags & QueueItem::FLAG_TTHLIST_BUNDLE));
}
return q;
}
string QueueManager::getListPath(const HintedUser& user) const noexcept {
StringList nicks = ClientManager::getInstance()->getNicks(user);
string nick = nicks.empty() ? Util::emptyString : Util::validateFileName(nicks[0]) + ".";
return Util::getListPath() + nick + user.user->getCID().toBase32();
}
bool QueueManager::checkRemovedTarget(QueueItemPtr& q, int64_t aSize, const TTHValue& aTTH) {
if (q->isDownloaded()) {
/* The target file doesn't exist, add our item. Also recheck the existance in case of finished files being moved on the same time. */
dcassert(q->getBundle());
if (!Util::fileExists(q->getTarget()) && q->getBundle() && q->isCompleted()) {
bundleQueue.removeBundleItem(q, false);
fileQueue.remove(q);
return true;
} else {
throw FileException(STRING(FILE_ALREADY_FINISHED));
}
} else {
/* try to add the source for the existing item */
if(q->getSize() != aSize) {
throw QueueException(STRING(FILE_WITH_DIFFERENT_SIZE));
}
if(aTTH != q->getTTH()) {
throw QueueException(STRING(FILE_WITH_DIFFERENT_TTH));
}
}
return false;
}
void QueueManager::setMatchers() noexcept {
auto sl = SETTING(SKIPLIST_DOWNLOAD);
skipList.pattern = SETTING(SKIPLIST_DOWNLOAD);
skipList.setMethod(SETTING(DOWNLOAD_SKIPLIST_USE_REGEXP) ? StringMatch::REGEX : StringMatch::WILDCARD);
skipList.prepare();
highPrioFiles.pattern = SETTING(HIGH_PRIO_FILES);
highPrioFiles.setMethod(SETTING(HIGHEST_PRIORITY_USE_REGEXP) ? StringMatch::REGEX : StringMatch::WILDCARD);
highPrioFiles.prepare();
}
void QueueManager::checkSource(const HintedUser& aUser) const {
// Check that we're not downloading from ourselves...
if(aUser.user == ClientManager::getInstance()->getMe()) {
throw QueueException(STRING(NO_DOWNLOADS_FROM_SELF));
}
// Check the encryption
if (aUser.user && aUser.user->isOnline() && !aUser.user->isNMDC() && !aUser.user->isSet(User::TLS) && SETTING(TLS_MODE) == SettingsManager::TLS_FORCED) {
throw QueueException(ClientManager::getInstance()->getFormatedNicks(aUser) + ": " + STRING(SOURCE_NO_ENCRYPTION));
}
}
void QueueManager::validateBundleFile(const string& aBundleDir, string& bundleFile_, const TTHValue& aTTH, Priority& priority_, int64_t aSize) const {
if (aSize <= 0) {
throw QueueException(STRING(ZERO_BYTE_QUEUE));
}
//check the skiplist
auto matchSkipList = [&] (string&& aName) -> void {
if(skipList.match(aName)) {
throw QueueException(STRING(SKIPLIST_DOWNLOAD_MATCH));
}
};
//match the file name
matchSkipList(Util::getFileName(bundleFile_));
//match all dirs (if any)
string::size_type i = 0, j = 0;
while ((i = bundleFile_.find(PATH_SEPARATOR, j)) != string::npos) {
matchSkipList(bundleFile_.substr(j, i - j));
j = i + 1;
}
//validate the target and check the existance
bundleFile_ = checkTarget(bundleFile_, aBundleDir);
//check share dupes
if (SETTING(DONT_DL_ALREADY_SHARED) && ShareManager::getInstance()->isFileShared(aTTH)) {
auto paths = ShareManager::getInstance()->getRealPaths(aTTH);
if (!paths.empty()) {
auto path = AirUtil::subtractCommonDirectories(aBundleDir, Util::getFilePath(paths.front()));
throw DupeException(STRING_F(TTH_ALREADY_SHARED, path));
}
}
//check queue dupes
if (SETTING(DONT_DL_ALREADY_QUEUED)) {
RLock l(cs);
auto q = fileQueue.getQueuedFile(aTTH);
if (q && q->getTarget() != aBundleDir + bundleFile_) {
auto path = AirUtil::subtractCommonDirectories(aBundleDir, q->getFilePath());
throw DupeException(STRING_F(FILE_ALREADY_QUEUED, path));
}
}
if(SETTING(USE_FTP_LOGGER)) {
AirUtil::fileEvent(aBundleDir + bundleFile_);
}
//valid file
//set the prio
if (highPrioFiles.match(Util::getFileName(bundleFile_))) {
priority_ = SETTING(PRIO_LIST_HIGHEST) ? Priority::HIGHEST : Priority::HIGH;
}
}
QueueItemPtr QueueManager::addOpenedItem(const string& aFileName, int64_t aSize, const TTHValue& aTTH, const HintedUser& aUser, bool aIsClientView, bool aIsText) {
//check the source
if (aUser.user)
checkSource(aUser);
//check the size
if (aSize == 0) {
//can't view this...
throw QueueException(STRING(CANT_OPEN_EMPTY_FILE));
} else if (aIsClientView && aIsText && aSize > Util::convertSize(1, Util::MB)) {
auto msg = STRING_F(VIEWED_FILE_TOO_BIG, aFileName % Util::formatBytes(aSize));
LogManager::getInstance()->message(msg, LogMessage::SEV_ERROR);
throw QueueException(msg);
}
//check the target
auto target = Util::getOpenPath() + AirUtil::toOpenFileName(aFileName, aTTH);
//add in queue
QueueItemPtr qi = nullptr;
bool wantConnection = false, added = false;
Flags::MaskType flags;
if (aIsClientView) {
flags = QueueItem::FLAG_CLIENT_VIEW;
} else {
flags = QueueItem::FLAG_OPEN;
}
{
WLock l(cs);
auto ret = fileQueue.add(target, aSize, flags, Priority::HIGHEST, Util::emptyString, GET_TIME(), aTTH);
qi = std::move(ret.first);
added = ret.second;
wantConnection = addSource(qi, aUser, QueueItem::Source::FLAG_MASK, false);
}
if (added) {
fire(QueueManagerListener::ItemAdded(), qi);
}
//connect
if(wantConnection || qi->usesSmallSlot()) {
ConnectionManager::getInstance()->getDownloadConnection(aUser, qi->usesSmallSlot());
}
return qi;
}
BundlePtr QueueManager::getBundle(const string& aTarget, Priority aPrio, time_t aDate, bool isFileBundle) noexcept {
auto b = bundleQueue.getMergeBundle(aTarget);
if (!b) {
// create a new bundle
b = BundlePtr(new Bundle(aTarget, GET_TIME(), aPrio, aDate, 0, true, isFileBundle));
} else {
// use an existing one
dcassert(!AirUtil::isSubLocal(b->getTarget(), aTarget));
}
return b;
}
optional<DirectoryBundleAddInfo> QueueManager::createDirectoryBundle(const string& aTarget, const HintedUser& aUser, BundleDirectoryItemInfo::List& aFiles, Priority aPrio, time_t aDate, string& errorMsg_) noexcept {
// Generic validations that will throw
auto target = formatBundleTarget(aTarget, aDate);
{
// There can't be existing bundles inside this directory
BundleList subBundles;
bundleQueue.getSubBundles(target, subBundles);
if (!subBundles.empty()) {
StringList subPaths;
for (const auto& b : subBundles) {
subPaths.push_back(b->getTarget());
}
errorMsg_ = STRING_F(BUNDLE_ERROR_SUBBUNDLES, subBundles.size() % target % AirUtil::subtractCommonParents(target, subPaths));
return nullopt;
}
}
if (aUser.user) {
try {
checkSource(aUser);
} catch (const QueueException& e) {
errorMsg_ = e.getError();
return nullopt;
}
}
if (aFiles.empty()) {
errorMsg_ = STRING(DIR_EMPTY);
return nullopt;
}
// File validation
int smallDupes = 0, fileCount = aFiles.size(), filesExist = 0;
DirectoryBundleAddInfo info;
ErrorCollector errors(fileCount);
aFiles.erase(boost::remove_if(aFiles, [&](BundleDirectoryItemInfo& bfi) {
try {
validateBundleFile(target, bfi.file, bfi.tth, bfi.prio, bfi.size);
return false; // valid
} catch(const QueueException& e) {
errors.add(e.getError(), bfi.file, false);
info.filesFailed++;
} catch(const FileException& e) {
errors.add(e.getError(), bfi.file, true);
filesExist++;
} catch(const DupeException& e) {
bool isSmall = bfi.size < Util::convertSize(SETTING(MIN_DUPE_CHECK_SIZE), Util::KB);
errors.add(e.getError(), bfi.file, isSmall);
if (isSmall) {
smallDupes++;
return false;
} else {
info.filesFailed++;
}
}
return true;
}), aFiles.end());
// Check file validation errors
if (aFiles.empty()) {
errorMsg_ = errors.getMessage();
return nullopt;
} else if (smallDupes > 0) {
if (smallDupes == static_cast<int>(aFiles.size())) {
// No reason to continue if all remaining files are dupes
errorMsg_ = errors.getMessage();
return nullopt;
} else {
// Those will get queued, don't report
errors.clearMinor();
}
}
BundlePtr b = nullptr;
bool wantConnection = false;
Bundle::Status oldStatus;
QueueItem::ItemBoolList queueItems;
{
WLock l(cs);
b = getBundle(target, aPrio, aDate, false);
oldStatus = b->getStatus();
//add the files
for (auto& bfi: aFiles) {
try {
auto addInfo = addBundleFile(target + bfi.file, bfi.size, bfi.tth, aUser, 0, true, bfi.prio, wantConnection, b);
if (addInfo.second) {
info.filesAdded++;
} else {
info.filesUpdated++;
}
queueItems.push_back(std::move(addInfo));
} catch(QueueException& e) {
errors.add(e.getError(), bfi.file, false);
info.filesFailed++;
} catch(FileException& e) {
//the file has finished after we made the initial target check
errors.add(e.getError(), bfi.file, true);
filesExist++;
}
}
addBundle(b, info.filesAdded);
}
if (queueItems.empty()) {
errorMsg_ = errors.getMessage();
return nullopt;
}
dcassert(b);
// Those don't need to be reported to the user
errors.clearMinor();
onBundleAdded(b, oldStatus, queueItems, aUser, wantConnection);
info.bundleInfo = BundleAddInfo(b, oldStatus != Bundle::STATUS_NEW);
if (info.filesAdded > 0) {
// Report
if (oldStatus == Bundle::STATUS_NEW) {
LogManager::getInstance()->message(STRING_F(BUNDLE_CREATED, b->getName() % info.filesAdded) + " (" + CSTRING_F(TOTAL_SIZE, Util::formatBytes(b->getSize())) + ")", LogMessage::SEV_INFO);
} else if (b->getTarget() == target) {
LogManager::getInstance()->message(STRING_F(X_BUNDLE_ITEMS_ADDED, info.filesAdded % b->getName().c_str()), LogMessage::SEV_INFO);
} else {
LogManager::getInstance()->message(STRING_F(BUNDLE_MERGED, Util::getLastDir(target) % b->getName() % info.filesAdded), LogMessage::SEV_INFO);
}
}
errorMsg_ = errors.getMessage();
return info;
}
void QueueManager::addLoadedBundle(BundlePtr& aBundle) noexcept {
WLock l(cs);
if (aBundle->isEmpty())
return;
if (bundleQueue.getMergeBundle(aBundle->getTarget()))
return;
bundleQueue.addBundle(aBundle);
}
void QueueManager::addBundle(BundlePtr& aBundle, int aItemsAdded) noexcept {
if (aItemsAdded == 0) {
return;
}
if (aBundle->getStatus() == Bundle::STATUS_NEW) {
bundleQueue.addBundle(aBundle);
} else {
if (static_cast<int>(aBundle->getQueueItems().size()) == aItemsAdded) {
// Finished bundle but failed hashing/scanning?
readdBundle(aBundle);
} else {
aBundle->setFlag(Bundle::FLAG_UPDATE_SIZE);
addBundleUpdate(aBundle);
aBundle->setDirty();
}
}
}
void QueueManager::onBundleAdded(const BundlePtr& aBundle, Bundle::Status aOldStatus, const QueueItem::ItemBoolList& aItemsAdded, const HintedUser& aUser, bool aWantConnection) noexcept {
if (aOldStatus == Bundle::STATUS_NEW) {
fire(QueueManagerListener::BundleAdded(), aBundle);
if (autoSearchEnabled() && !aBundle->isPausedPrio()) {
aBundle->setFlag(Bundle::FLAG_SCHEDULE_SEARCH);
addBundleUpdate(aBundle);
}
} else {
if (aOldStatus > Bundle::STATUS_DOWNLOADED) {
fire(QueueManagerListener::BundleStatusChanged(), aBundle);
}
fire(QueueManagerListener::BundleSources(), aBundle);
for (const auto& itemInfo : aItemsAdded) {
if (itemInfo.second) {
fire(QueueManagerListener::ItemAdded(), itemInfo.first);
} else {
fire(QueueManagerListener::ItemSources(), itemInfo.first);
}
}
}
fire(QueueManagerListener::SourceFilesUpdated(), aUser);
if (aWantConnection && aUser.user->isOnline()) {
//connect to the source (we must have an user in this case)
ConnectionManager::getInstance()->getDownloadConnection(aUser);
}
}
string QueueManager::formatBundleTarget(const string& aPath, time_t aRemoteDate) noexcept {
ParamMap params;
params["username"] = [] { return Util::getSystemUsername(); };
auto time = (SETTING(FORMAT_DIR_REMOTE_TIME) && aRemoteDate > 0) ? aRemoteDate : GET_TIME();
auto formatedPath = Util::formatParams(aPath, params, nullptr, time);
return Util::validatePath(formatedPath);
}
BundleAddInfo QueueManager::createFileBundle(const string& aTarget, int64_t aSize, const TTHValue& aTTH, const HintedUser& aUser, time_t aDate,
Flags::MaskType aFlags, Priority aPrio) {
string filePath = formatBundleTarget(Util::getFilePath(aTarget), aDate);
string fileName = Util::getFileName(aTarget);
//check the source
if (aUser.user) {
checkSource(aUser);
}
validateBundleFile(filePath, fileName, aTTH, aPrio, aSize);
BundlePtr b = nullptr;
bool wantConnection = false;
auto target = filePath + fileName;
Bundle::Status oldStatus;
FileAddInfo fileAddInfo;
{
WLock l(cs);
b = getBundle(target, aPrio, aDate, true);
oldStatus = b->getStatus();
fileAddInfo = addBundleFile(target, aSize, aTTH, aUser, aFlags, true, aPrio, wantConnection, b);
addBundle(b, fileAddInfo.second ? 1 : 0);
}
onBundleAdded(b, oldStatus, { fileAddInfo }, aUser, wantConnection);
if (fileAddInfo.second) {
if (oldStatus == Bundle::STATUS_NEW) {
LogManager::getInstance()->message(STRING_F(FILE_X_QUEUED, b->getName() % Util::formatBytes(b->getSize())), LogMessage::SEV_INFO);
} else {
LogManager::getInstance()->message(STRING_F(BUNDLE_ITEM_ADDED, Util::getFileName(target) % b->getName()), LogMessage::SEV_INFO);
}
}
return BundleAddInfo(b, oldStatus != Bundle::STATUS_NEW);
}
QueueManager::FileAddInfo QueueManager::addBundleFile(const string& aTarget, int64_t aSize, const TTHValue& aRoot, const HintedUser& aUser, Flags::MaskType aFlags /* = 0 */,
bool addBad /* = true */, Priority aPrio, bool& wantConnection_, BundlePtr& aBundle)
{
dcassert(aSize > 0);
// Add the file
auto ret = fileQueue.add(aTarget, aSize, aFlags, aPrio, Util::emptyString, GET_TIME(), aRoot);
if(!ret.second) {
// Exists already
if (checkRemovedTarget(ret.first, aSize, aRoot)) {