forked from meganz/sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtransfer.cpp
More file actions
2077 lines (1800 loc) · 63.8 KB
/
transfer.cpp
File metadata and controls
2077 lines (1800 loc) · 63.8 KB
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
/**
* @file transfer.cpp
* @brief Pending/active up/download ordered by file fingerprint
*
* (c) 2013-2014 by Mega Limited, Auckland, New Zealand
*
* This file is part of the MEGA SDK - Client Access Engine.
*
* Applications using the MEGA API must present a valid application key
* and comply with the the rules set forth in the Terms of Service.
*
* The MEGA SDK 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.
*
* @copyright Simplified (2-clause) BSD License.
*
* You should have received a copy of the license along with this
* program.
*/
#include "mega/transfer.h"
#include "mega/megaclient.h"
#include "mega/transferslot.h"
#include "mega/megaapp.h"
#include "mega/sync.h"
#include "mega/logging.h"
#include "mega/base64.h"
#include "mega/mediafileattribute.h"
#include "megawaiter.h"
#include "mega/utils.h"
namespace mega {
TransferCategory::TransferCategory(direction_t d, filesizetype_t s)
: direction(d)
, sizetype(s)
{
}
TransferCategory::TransferCategory(Transfer* t)
: direction(t->type)
, sizetype(t->size > 131072 ? LARGEFILE : SMALLFILE) // Conservative starting point: 131072 is the smallest chunk, we will certainly only use one socket to upload/download
{
}
unsigned TransferCategory::index()
{
assert(direction == GET || direction == PUT);
assert(sizetype == LARGEFILE || sizetype == SMALLFILE);
return 2 + direction * 2 + sizetype;
}
unsigned TransferCategory::directionIndex()
{
assert(direction == GET || direction == PUT);
return direction;
}
Transfer::Transfer(MegaClient* cclient, direction_t ctype)
: bt(cclient->rng, cclient->transferRetryBackoffs[ctype])
{
type = ctype;
client = cclient;
size = 0;
failcount = 0;
uploadhandle = 0;
minfa = 0;
pos = 0;
ctriv = 0;
metamac = 0;
tag = 0;
slot = NULL;
asyncopencontext = NULL;
progresscompleted = 0;
hasprevmetamac = false;
hascurrentmetamac = false;
finished = false;
lastaccesstime = 0;
ultoken = NULL;
priority = 0;
state = TRANSFERSTATE_NONE;
skipserialization = false;
faputcompletion_it = client->faputcompletion.end();
transfers_it = client->transfers[type].end();
}
// delete transfer with underlying slot, notify files
Transfer::~Transfer()
{
if (faputcompletion_it != client->faputcompletion.end())
{
client->faputcompletion.erase(faputcompletion_it);
}
for (file_list::iterator it = files.begin(); it != files.end(); it++)
{
if (finished)
{
client->filecachedel(*it, nullptr);
}
(*it)->transfer = NULL;
(*it)->terminated();
}
if (!mOptimizedDelete)
{
if (transfers_it != client->transfers[type].end())
{
client->transfers[type].erase(transfers_it);
}
client->transferlist.removetransfer(this);
}
if (slot)
{
delete slot;
}
if (asyncopencontext)
{
delete asyncopencontext;
asyncopencontext = NULL;
client->asyncfopens--;
}
if (ultoken)
{
delete [] ultoken;
}
if (finished)
{
if (type == GET && !localfilename.empty())
{
client->fsaccess->unlinklocal(localfilename);
}
client->transfercachedel(this, nullptr);
}
}
bool Transfer::serialize(string *d)
{
unsigned short ll;
d->append((const char*)&type, sizeof(type));
ll = (unsigned short)localfilename.editStringDirect()->size();
d->append((char*)&ll, sizeof(ll));
d->append(localfilename.editStringDirect()->data(), ll);
d->append((const char*)filekey, sizeof(filekey));
d->append((const char*)&ctriv, sizeof(ctriv));
d->append((const char*)&metamac, sizeof(metamac));
d->append((const char*)transferkey.data(), sizeof (transferkey));
chunkmacs.serialize(*d);
if (!FileFingerprint::serialize(d))
{
LOG_err << "Error serializing Transfer: Unable to serialize FileFingerprint";
return false;
}
if (!badfp.serialize(d))
{
LOG_err << "Error serializing Transfer: Unable to serialize badfp";
return false;
}
d->append((const char*)&lastaccesstime, sizeof(lastaccesstime));
char hasUltoken;
if (ultoken)
{
hasUltoken = 2;
d->append((const char*)&hasUltoken, sizeof(char));
d->append((const char*)ultoken, NewNode::UPLOADTOKENLEN);
}
else
{
hasUltoken = 0;
d->append((const char*)&hasUltoken, sizeof(char));
}
// store raid URL string(s) in the same record as non-raid, 0-delimited in the case of raid
std::string combinedUrls;
for (std::vector<std::string>::const_iterator i = tempurls.begin(); i != tempurls.end(); ++i)
{
combinedUrls.append("", i == tempurls.begin() ? 0 : 1); // '\0' separator
combinedUrls.append(*i);
}
ll = (unsigned short)combinedUrls.size();
d->append((char*)&ll, sizeof(ll));
d->append(combinedUrls.data(), ll);
char s = static_cast<char>(state);
d->append((const char*)&s, sizeof(s));
d->append((const char*)&priority, sizeof(priority));
d->append("", 1);
return true;
}
Transfer *Transfer::unserialize(MegaClient *client, string *d, transfer_map* transfers)
{
unsigned short ll;
const char* ptr = d->data();
const char* end = ptr + d->size();
if (ptr + sizeof(direction_t) + sizeof(ll) > end)
{
LOG_err << "Transfer unserialization failed - serialized string too short (direction)";
return NULL;
}
direction_t type;
type = MemAccess::get<direction_t>(ptr);
ptr += sizeof(direction_t);
if (type != GET && type != PUT)
{
assert(false);
LOG_err << "Transfer unserialization failed - neither get nor put";
return NULL;
}
ll = MemAccess::get<unsigned short>(ptr);
ptr += sizeof(ll);
if (ptr + ll + FILENODEKEYLENGTH + sizeof(int64_t)
+ sizeof(int64_t) + SymmCipher::KEYLENGTH
+ sizeof(ll) > end)
{
LOG_err << "Transfer unserialization failed - serialized string too short (filepath)";
return NULL;
}
const char *filepath = ptr;
ptr += ll;
Transfer *t = new Transfer(client, type);
memcpy(t->filekey, ptr, sizeof t->filekey);
ptr += sizeof(t->filekey);
t->ctriv = MemAccess::get<int64_t>(ptr);
ptr += sizeof(int64_t);
t->metamac = MemAccess::get<int64_t>(ptr);
ptr += sizeof(int64_t);
memcpy(t->transferkey.data(), ptr, SymmCipher::KEYLENGTH);
ptr += SymmCipher::KEYLENGTH;
t->localfilename = LocalPath::fromLocalname(std::string(filepath, ll));
if (!t->chunkmacs.unserialize(ptr, end))
{
LOG_err << "Transfer unserialization failed - chunkmacs too long";
delete t;
return NULL;
}
d->erase(0, ptr - d->data());
FileFingerprint *fp = FileFingerprint::unserialize(d);
if (!fp)
{
LOG_err << "Error unserializing Transfer: Unable to unserialize FileFingerprint";
delete t;
return NULL;
}
*(FileFingerprint *)t = *(FileFingerprint *)fp;
delete fp;
fp = FileFingerprint::unserialize(d);
t->badfp = *fp;
delete fp;
ptr = d->data();
end = ptr + d->size();
if (ptr + sizeof(m_time_t) + sizeof(char) > end)
{
LOG_err << "Transfer unserialization failed - fingerprint too long";
delete t;
return NULL;
}
t->lastaccesstime = MemAccess::get<m_time_t>(ptr);
ptr += sizeof(m_time_t);
char hasUltoken = MemAccess::get<char>(ptr);
ptr += sizeof(char);
ll = hasUltoken ? ((hasUltoken == 1) ? NewNode::OLDUPLOADTOKENLEN + 1 : NewNode::UPLOADTOKENLEN) : 0;
if (hasUltoken < 0 || hasUltoken > 2
|| (ptr + ll + sizeof(unsigned short) > end))
{
LOG_err << "Transfer unserialization failed - invalid ultoken";
delete t;
return NULL;
}
if (hasUltoken)
{
t->ultoken = new byte[NewNode::UPLOADTOKENLEN]();
memcpy(t->ultoken, ptr, ll);
ptr += ll;
}
ll = MemAccess::get<unsigned short>(ptr);
ptr += sizeof(ll);
if (ptr + ll + 10 > end)
{
LOG_err << "Transfer unserialization failed - temp URL too long";
delete t;
return NULL;
}
std::string combinedUrls;
combinedUrls.assign(ptr, ll);
for (size_t p = 0; p < ll; )
{
size_t n = combinedUrls.find('\0');
t->tempurls.push_back(combinedUrls.substr(p, n));
assert(!t->tempurls.back().empty());
p += (n == std::string::npos) ? ll : (n + 1);
}
if (!t->tempurls.empty() && t->tempurls.size() != 1 && t->tempurls.size() != RAIDPARTS)
{
LOG_err << "Transfer unserialization failed - temp URL incorrect components";
delete t;
return NULL;
}
ptr += ll;
char state = MemAccess::get<char>(ptr);
ptr += sizeof(char);
if (state == TRANSFERSTATE_PAUSED)
{
LOG_debug << "Unserializing paused transfer";
t->state = TRANSFERSTATE_PAUSED;
}
t->priority = MemAccess::get<uint64_t>(ptr);
ptr += sizeof(uint64_t);
if (*ptr)
{
LOG_err << "Transfer unserialization failed - invalid version";
delete t;
return NULL;
}
ptr++;
t->chunkmacs.calcprogress(t->size, t->pos, t->progresscompleted);
transfers[type].insert(pair<FileFingerprint*, Transfer*>(t, t));
return t;
}
SymmCipher *Transfer::transfercipher()
{
client->tmptransfercipher.setkey(transferkey.data());
return &client->tmptransfercipher;
}
void Transfer::removeTransferFile(error e, File* f, DBTableTransactionCommitter* committer)
{
Transfer *transfer = f->transfer;
client->filecachedel(f, committer);
transfer->files.erase(f->file_it);
client->app->file_removed(f, e);
f->transfer = NULL;
f->terminated();
}
// transfer attempt failed, notify all related files, collect request on
// whether to abort the transfer, kill transfer if unanimous
void Transfer::failed(const Error& e, DBTableTransactionCommitter& committer, dstime timeleft)
{
bool defer = false;
LOG_debug << "Transfer failed with error " << e;
if (e == API_EOVERQUOTA || e == API_EPAYWALL)
{
assert((API_EPAYWALL && !timeleft) || (type == PUT && !timeleft) || (type == GET && timeleft)); // overstorage only possible for uploads, overbandwidth for downloads
if (!slot)
{
bt.backoff(timeleft ? timeleft : NEVER);
client->activateoverquota(timeleft, (e == API_EPAYWALL));
client->app->transfer_failed(this, e, timeleft);
++client->performanceStats.transferTempErrors;
}
else
{
bool allForeignTargets = true;
for (auto &file : files)
{
if (client->isPrivateNode(file->h))
{
allForeignTargets = false;
break;
}
}
/* If all targets are foreign and there's not a bandwidth overquota, transfer must fail.
* Otherwise we need to activate overquota.
*/
if (!timeleft && allForeignTargets)
{
client->app->transfer_failed(this, e);
}
else
{
bt.backoff(timeleft ? timeleft : NEVER);
client->activateoverquota(timeleft, (e == API_EPAYWALL));
}
}
}
else if (e == API_EARGS || (e == API_EBLOCKED && type == GET) || (e == API_ETOOMANY && type == GET && e.hasExtraInfo()))
{
client->app->transfer_failed(this, e);
}
else if (e != API_EBUSINESSPASTDUE)
{
bt.backoff();
state = TRANSFERSTATE_RETRYING;
client->app->transfer_failed(this, e, timeleft);
client->looprequested = true;
++client->performanceStats.transferTempErrors;
}
for (file_list::iterator it = files.begin(); it != files.end();)
{
// Remove files with foreign targets, if transfer failed with a (foreign) storage overquota
if (e == API_EOVERQUOTA
&& !timeleft
&& client->isForeignNode((*it)->h))
{
File *f = (*it++);
removeTransferFile(API_EOVERQUOTA, f, &committer);
continue;
}
/*
* If the transfer failed with API_EARGS, the target handle is invalid. For a sync-transfer,
* the actionpacket will eventually remove the target and the sync-engine will force to
* disable the synchronization of the folder. For non-sync-transfers, remove the file directly.
*/
if (e == API_EARGS || (e == API_EBLOCKED && type == GET) || (e == API_ETOOMANY && type == GET && e.hasExtraInfo()))
{
File *f = (*it++);
if (f->syncxfer && e == API_EARGS)
{
defer = true;
}
else
{
removeTransferFile(e, f, &committer);
}
continue;
}
if (((*it)->failed(e) && (e != API_EBUSINESSPASTDUE))
|| (e == API_ENOENT // putnodes returned -9, file-storage server unavailable
&& type == PUT
&& tempurls.empty()
&& failcount < 16) )
{
defer = true;
}
it++;
}
tempurls.clear();
if (type == PUT)
{
chunkmacs.clear();
progresscompleted = 0;
delete [] ultoken;
ultoken = NULL;
pos = 0;
if (slot && slot->fa && (slot->fa->mtime != mtime || slot->fa->size != size))
{
LOG_warn << "Modification detected during active upload. Size: " << size << " Mtime: " << mtime
<< " FaSize: " << slot->fa->size << " FaMtime: " << slot->fa->mtime;
defer = false;
}
}
if (defer)
{
failcount++;
delete slot;
slot = NULL;
client->transfercacheadd(this, &committer);
LOG_debug << "Deferring transfer " << failcount << " during " << (bt.retryin() * 100) << " ms";
}
else
{
LOG_debug << "Removing transfer";
state = TRANSFERSTATE_FAILED;
finished = true;
for (file_list::iterator it = files.begin(); it != files.end(); it++)
{
#ifdef ENABLE_SYNC
if((*it)->syncxfer
&& e != API_EBUSINESSPASTDUE
&& e != API_EOVERQUOTA
&& e != API_EPAYWALL)
{
client->syncdownrequired = true;
}
#endif
client->app->file_removed(*it, e);
}
client->app->transfer_removed(this);
++client->performanceStats.transferFails;
delete this;
}
}
#ifdef USE_MEDIAINFO
static uint32_t* fileAttributeKeyPtr(byte filekey[FILENODEKEYLENGTH])
{
// returns the last half, beyond the actual key, ie the nonce+crc
return (uint32_t*)(filekey + FILENODEKEYLENGTH / 2);
}
#endif
void Transfer::addAnyMissingMediaFileAttributes(Node* node, /*const*/ LocalPath& localpath)
{
assert(type == PUT || (node && node->type == FILENODE));
#ifdef USE_MEDIAINFO
char ext[8];
if (((type == PUT && size >= 16) || (node && node->nodekey().size() == FILENODEKEYLENGTH && node->size >= 16)) &&
client->fsaccess->getextension(localpath, ext, sizeof(ext)) &&
MediaProperties::isMediaFilenameExt(ext) &&
!client->mediaFileInfo.mediaCodecsFailed)
{
// for upload, the key is in the transfer. for download, the key is in the node.
uint32_t* attrKey = fileAttributeKeyPtr((type == PUT) ? filekey : (byte*)node->nodekey().data());
if (type == PUT || !node->hasfileattribute(fa_media) || client->mediaFileInfo.timeToRetryMediaPropertyExtraction(node->fileattrstring, attrKey))
{
// if we don't have the codec id mappings yet, send the request
client->mediaFileInfo.requestCodecMappingsOneTime(client, NULL);
// always get the attribute string; it may indicate this version of the mediaInfo library was unable to interpret the file
MediaProperties vp;
vp.extractMediaPropertyFileAttributes(localpath, client->fsaccess);
if (type == PUT)
{
minfa += client->mediaFileInfo.queueMediaPropertiesFileAttributesForUpload(vp, attrKey, client, uploadhandle);
}
else
{
client->mediaFileInfo.sendOrQueueMediaPropertiesFileAttributesForExistingFile(vp, attrKey, client, node->nodehandle);
}
}
}
#endif
}
// transfer completion: copy received file locally, set timestamp(s), verify
// fingerprint, notify app, notify files
void Transfer::complete(DBTableTransactionCommitter& committer)
{
CodeCounter::ScopeTimer ccst(client->performanceStats.transferComplete);
state = TRANSFERSTATE_COMPLETING;
client->app->transfer_update(this);
if (type == GET)
{
LOG_debug << "Download complete: " << (files.size() ? LOG_NODEHANDLE(files.front()->h) : "NO_FILES") << " " << files.size();
bool transient_error = false;
LocalPath tmplocalname;
LocalPath localname;
bool success;
// disconnect temp file from slot...
slot->fa.reset();
// FIXME: multiple overwrite race conditions below (make copies
// from open file instead of closing/reopening!)
// set timestamp (subsequent moves & copies are assumed not to alter mtime)
success = client->fsaccess->setmtimelocal(localfilename, mtime);
#ifdef ENABLE_SYNC
if (!success)
{
transient_error = client->fsaccess->transient_error;
LOG_debug << "setmtimelocal failed " << transient_error;
}
#endif
// verify integrity of file
auto fa = client->fsaccess->newfileaccess();
FileFingerprint fingerprint;
Node* n = nullptr;
bool fixfingerprint = false;
bool fixedfingerprint = false;
bool syncxfer = false;
for (file_list::iterator it = files.begin(); it != files.end(); it++)
{
if ((*it)->syncxfer)
{
syncxfer = true;
}
if (!fixedfingerprint && (n = client->nodebyhandle((*it)->h))
&& !(*(FileFingerprint*)this == *(FileFingerprint*)n))
{
LOG_debug << "Wrong fingerprint already fixed";
fixedfingerprint = true;
}
if (syncxfer && fixedfingerprint)
{
break;
}
}
if (!fixedfingerprint && success && fa->fopen(localfilename, true, false))
{
fingerprint.genfingerprint(fa.get());
if (isvalid && !(fingerprint == *(FileFingerprint*)this))
{
LOG_err << "Fingerprint mismatch";
// enforce the verification of the fingerprint for sync transfers only
if (syncxfer && (!badfp.isvalid || !(badfp == fingerprint)))
{
badfp = fingerprint;
fa.reset();
chunkmacs.clear();
client->fsaccess->unlinklocal(localfilename);
return failed(API_EWRITE, committer);
}
else
{
// We consider that mtime is different if the difference is >2
// due to the resolution of mtime in some filesystems (like FAT).
// This check prevents changes in the fingerprint due to silent
// errors in setmtimelocal (returning success but not setting the
// modification time) that seem to happen in some Android devices.
if (abs(mtime - fingerprint.mtime) <= 2)
{
fixfingerprint = true;
}
else
{
LOG_warn << "Silent failure in setmtimelocal";
}
}
}
}
#ifdef ENABLE_SYNC
else
{
if (syncxfer && !fixedfingerprint && success)
{
transient_error = fa->retry;
LOG_debug << "Unable to validate fingerprint " << transient_error;
}
}
#endif
fa.reset();
char me64[12];
Base64::btoa((const byte*)&client->me, MegaClient::USERHANDLE, me64);
if (!transient_error)
{
if (fingerprint.isvalid)
{
// set FileFingerprint on source node(s) if missing
set<handle> nodes;
for (file_list::iterator it = files.begin(); it != files.end(); it++)
{
if ((*it)->hprivate && !(*it)->hforeign && (n = client->nodebyhandle((*it)->h))
&& nodes.find(n->nodehandle) == nodes.end())
{
nodes.insert(n->nodehandle);
if ((!n->isvalid || fixfingerprint)
&& !(fingerprint == *(FileFingerprint*)n)
&& fingerprint.size == this->size)
{
LOG_debug << "Fixing fingerprint";
*(FileFingerprint*)n = fingerprint;
n->serializefingerprint(&n->attrs.map['c']);
client->setattr(n);
}
}
}
}
// ...and place it in all target locations. first, update the files'
// local target filenames, in case they have changed during the upload
for (file_list::iterator it = files.begin(); it != files.end(); it++)
{
(*it)->updatelocalname();
}
set<string> keys;
// place file in all target locations - use up to one renames, copy
// operations for the rest
// remove and complete successfully completed files
for (file_list::iterator it = files.begin(); it != files.end(); )
{
transient_error = false;
success = false;
localname = (*it)->localname;
if (localname != localfilename)
{
fa = client->fsaccess->newfileaccess();
if (fa->fopen(localname) || fa->type == FOLDERNODE)
{
// the destination path already exists
#ifdef ENABLE_SYNC
if((*it)->syncxfer)
{
sync_list::iterator it2;
for (it2 = client->syncs.begin(); it2 != client->syncs.end(); it2++)
{
Sync *sync = (*it2);
LocalNode *localNode = sync->localnodebypath(NULL, localname);
if (localNode)
{
LOG_debug << "Overwriting a local synced file. Moving the previous one to debris";
// try to move to local debris
if(!sync->movetolocaldebris(localname))
{
transient_error = client->fsaccess->transient_error;
}
break;
}
}
if(it2 == client->syncs.end())
{
LOG_err << "LocalNode for destination file not found";
if(client->syncs.size())
{
// try to move to debris in the first sync
if(!client->syncs.front()->movetolocaldebris(localname))
{
transient_error = client->fsaccess->transient_error;
}
}
}
}
else
#endif
{
LOG_debug << "The destination file exist (not synced). Saving with a different name";
// the destination path isn't synced, save with a (x) suffix
string utf8fullname = localname.toPath(*client->fsaccess);
size_t dotindex = utf8fullname.find_last_of('.');
string name;
string extension;
if (dotindex == string::npos)
{
name = utf8fullname;
}
else
{
string separator;
client->fsaccess->local2path(&client->fsaccess->localseparator, &separator);
size_t sepindex = utf8fullname.find_last_of(separator);
if(sepindex == string::npos || sepindex < dotindex)
{
name = utf8fullname.substr(0, dotindex);
extension = utf8fullname.substr(dotindex);
}
else
{
name = utf8fullname;
}
}
string suffix;
string newname;
LocalPath localnewname;
int num = 0;
do
{
num++;
ostringstream oss;
oss << " (" << num << ")";
suffix = oss.str();
newname = name + suffix + extension;
localnewname = LocalPath::fromPath(newname, *client->fsaccess);
} while (fa->fopen(localnewname) || fa->type == FOLDERNODE);
(*it)->localname = localnewname;
localname = localnewname;
}
}
else
{
transient_error = fa->retry;
}
if (transient_error)
{
LOG_warn << "Transient error checking if the destination file exist";
it++;
continue;
}
}
if (files.size() == 1 && tmplocalname.empty())
{
if (localfilename != localname)
{
LOG_debug << "Renaming temporary file to target path";
if (client->fsaccess->renamelocal(localfilename, localname))
{
tmplocalname = localname;
success = true;
}
else if (client->fsaccess->transient_error)
{
transient_error = true;
}
}
else
{
tmplocalname = localname;
success = true;
}
}
if (!success)
{
if((!tmplocalname.empty() ? tmplocalname : localfilename) == localname)
{
LOG_debug << "Identical node downloaded to the same folder";
success = true;
}
else if (client->fsaccess->copylocal(!tmplocalname.empty() ? tmplocalname : localfilename,
localname, mtime))
{
success = true;
}
else if (client->fsaccess->transient_error)
{
transient_error = true;
}
}
if (success)
{
// set missing node attributes
if ((*it)->hprivate && !(*it)->hforeign && (n = client->nodebyhandle((*it)->h)))
{
if (!client->gfxdisabled && client->gfx && client->gfx->isgfx(localname.editStringDirect()) &&
keys.find(n->nodekey()) == keys.end() && // this file hasn't been processed yet
client->checkaccess(n, OWNER))
{
keys.insert(n->nodekey());
// check if restoration of missing attributes failed in the past (no access)
if (n->attrs.map.find('f') == n->attrs.map.end() || n->attrs.map['f'] != me64)
{
// check for missing imagery
int missingattr = 0;
if (!n->hasfileattribute(GfxProc::THUMBNAIL)) missingattr |= 1 << GfxProc::THUMBNAIL;
if (!n->hasfileattribute(GfxProc::PREVIEW)) missingattr |= 1 << GfxProc::PREVIEW;
if (missingattr)
{
client->gfx->gendimensionsputfa(NULL, localname.editStringDirect(), n->nodehandle, n->nodecipher(), missingattr);
}
addAnyMissingMediaFileAttributes(n, localname);
}
}
}
}
if (success || !transient_error)
{
if (success)
{
// prevent deletion of associated Transfer object in completed()
client->filecachedel(*it, &committer);
client->app->file_complete(*it);
(*it)->transfer = NULL;
(*it)->completed(this, NULL);
}
if (success || !(*it)->failed(API_EAGAIN))
{
File* f = (*it);
files.erase(it++);
if (!success)
{
LOG_warn << "Unable to complete transfer due to a persistent error";
client->filecachedel(f, &committer);
#ifdef ENABLE_SYNC
if (f->syncxfer)
{
client->syncdownrequired = true;
}
#endif
client->app->file_removed(f, API_EWRITE);
f->transfer = NULL;
f->terminated();
}
}
else
{
failcount++;
LOG_debug << "Persistent error completing file. Failcount: " << failcount;
it++;
}
}
else
{
LOG_debug << "Transient error completing file";
it++;
}
}
if (tmplocalname.empty() && !files.size())
{
client->fsaccess->unlinklocal(localfilename);
}
}
if (!files.size())
{
state = TRANSFERSTATE_COMPLETED;
localfilename = localname;
finished = true;
client->looprequested = true;
client->app->transfer_complete(this);
localfilename.clear();
delete this;
}
else
{
// some files are still pending completion, close fa and set retry timer
slot->fa.reset();
LOG_debug << "Files pending completion: " << files.size() << ". Waiting for a retry.";
LOG_debug << "First pending file: " << files.front()->name;
slot->retrying = true;
slot->retrybt.backoff(11);
}
}
else
{
LOG_debug << "Upload complete: " << (files.size() ? files.front()->name : "NO_FILES") << " " << files.size();
if (slot->fa)
{
slot->fa.reset();
}
// files must not change during a PUT transfer
for (file_list::iterator it = files.begin(); it != files.end(); )
{
File *f = (*it);
LocalPath *localpath = &f->localname;
#ifdef ENABLE_SYNC
LocalPath synclocalpath;