forked from meganz/sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtransferslot.cpp
More file actions
1305 lines (1149 loc) · 54.5 KB
/
transferslot.cpp
File metadata and controls
1305 lines (1149 loc) · 54.5 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 transferslot.cpp
* @brief Class for active transfer
*
* (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/transferslot.h"
#include "mega/node.h"
#include "mega/transfer.h"
#include "mega/megaclient.h"
#include "mega/command.h"
#include "mega/base64.h"
#include "mega/megaapp.h"
#include "mega/utils.h"
#include "mega/logging.h"
#include "mega/raid.h"
namespace mega {
TransferSlotFileAccess::TransferSlotFileAccess(std::unique_ptr<FileAccess>&& p, Transfer* t)
: transfer(t)
{
reset(std::move(p));
}
TransferSlotFileAccess::~TransferSlotFileAccess()
{
reset();
}
void TransferSlotFileAccess::reset(std::unique_ptr<FileAccess>&& p)
{
fa = std::move(p);
// transfer has no slot or slot has no fa: timer is enabled
transfer->bt.enable(!!p);
}
// transfer attempts are considered failed after XFERTIMEOUT deciseconds
// without data flow
const dstime TransferSlot::XFERTIMEOUT = 600;
// max time without progress callbacks
const dstime TransferSlot::PROGRESSTIMEOUT = 10;
// max request size for downloads
#if defined(__ANDROID__) || defined(USE_IOS) || defined(WINDOWS_PHONE)
const m_off_t TransferSlot::MAX_REQ_SIZE = 2097152; // 2 MB
#elif defined (_WIN32) || defined(HAVE_AIO_RT)
const m_off_t TransferSlot::MAX_REQ_SIZE = 16777216; // 16 MB
#else
const m_off_t TransferSlot::MAX_REQ_SIZE = 4194304; // 4 MB
#endif
TransferSlot::TransferSlot(Transfer* ctransfer)
: fa(ctransfer->client->fsaccess->newfileaccess(), ctransfer)
, retrybt(ctransfer->client->rng, ctransfer->client->transferSlotsBackoff)
{
starttime = 0;
lastprogressreport = 0;
progressreported = 0;
speed = meanSpeed = 0;
progresscontiguous = 0;
lastdata = Waiter::ds;
errorcount = 0;
lasterror = API_OK;
failure = false;
retrying = false;
fileattrsmutable = 0;
connections = 0;
asyncIO = NULL;
pendingcmd = NULL;
transfer = ctransfer;
transfer->slot = this;
transfer->state = TRANSFERSTATE_ACTIVE;
slots_it = transfer->client->tslots.end();
maxRequestSize = MAX_REQ_SIZE;
#if defined(_WIN32) && !defined(WINDOWS_PHONE)
MEMORYSTATUSEX statex;
memset(&statex, 0, sizeof (statex));
statex.dwLength = sizeof (statex);
if (GlobalMemoryStatusEx(&statex))
{
LOG_debug << "RAM stats. Free physical: " << statex.ullAvailPhys << " Free virtual: " << statex.ullAvailVirtual;
if (statex.ullAvailPhys < 1073741824 // 1024 MB
|| statex.ullAvailVirtual < 1073741824)
{
if (statex.ullAvailPhys < 536870912 // 512 MB
|| statex.ullAvailVirtual < 536870912)
{
if (statex.ullAvailPhys < 268435456 // 256 MB
|| statex.ullAvailVirtual < 268435456)
{
maxRequestSize = 2097152; // 2 MB
}
else
{
maxRequestSize = 4194304; // 4 MB
}
}
else
{
maxRequestSize = 8388608; // 8 MB
}
}
else
{
maxRequestSize = 16777216; // 16 MB
}
}
else
{
LOG_warn << "Error getting RAM usage info";
}
#endif
}
bool TransferSlot::createconnectionsonce()
{
// delay creating these until we know if it's raid or non-raid
if (!(connections || reqs.size() || asyncIO))
{
if (transferbuf.tempUrlVector().empty())
{
return false; // too soon, we don't know raid / non-raid yet
}
connections = transferbuf.isRaid() ? RAIDPARTS : (transfer->size > 131072 ? transfer->client->connections[transfer->type] : 1);
LOG_debug << "Populating transfer slot with " << connections << " connections, max request size of " << maxRequestSize << " bytes";
reqs.resize(connections);
mReqSpeeds.resize(connections);
asyncIO = new AsyncIOContext*[connections]();
}
return true;
}
// delete slot and associated resources, but keep transfer intact (can be
// reused on a new slot)
TransferSlot::~TransferSlot()
{
if (transfer->type == GET && !transfer->finished
&& transfer->progresscompleted != transfer->size
&& !transfer->asyncopencontext)
{
bool cachetransfer = false; // need to save in cache
if (fa && fa->asyncavailable())
{
for (int i = 0; i < connections; i++)
{
if (reqs[i] && reqs[i]->status == REQ_ASYNCIO && asyncIO[i])
{
asyncIO[i]->finish();
if (!asyncIO[i]->failed)
{
LOG_verbose << "Async write succeeded";
transferbuf.bufferWriteCompleted(i, true);
cachetransfer = true;
}
else
{
LOG_verbose << "Async write failed";
transferbuf.bufferWriteCompleted(i, false);
}
reqs[i]->status = REQ_READY;
}
delete asyncIO[i];
asyncIO[i] = NULL;
}
// Open the file in synchonous mode
fa.reset(transfer->client->fsaccess->newfileaccess());
if (!fa->fopen(transfer->localfilename, false, true))
{
fa.reset();
}
}
for (int i = 0; i < connections; i++)
{
if (HttpReqDL *downloadRequest = static_cast<HttpReqDL*>(reqs[i].get()))
{
switch (static_cast<reqstatus_t>(downloadRequest->status))
{
case REQ_INFLIGHT:
if (fa && downloadRequest && downloadRequest->status == REQ_INFLIGHT
&& downloadRequest->contentlength == downloadRequest->size
&& downloadRequest->bufpos >= SymmCipher::BLOCKSIZE)
{
HttpReq::http_buf_t* buf = downloadRequest->release_buf();
buf->end -= buf->datalen() % RAIDSECTOR;
transferbuf.submitBuffer(i, new TransferBufferManager::FilePiece(downloadRequest->dlpos, buf)); // resets size & bufpos of downloadrequest.
}
break;
case REQ_DECRYPTING:
LOG_info << "Waiting for block decryption";
std::mutex finalizedMutex;
std::unique_lock<std::mutex> guard(finalizedMutex);
auto outputPiece = transferbuf.getAsyncOutputBufferPointer(i);
outputPiece->finalizedCV.wait(guard, [&](){ return outputPiece->finalized; });
downloadRequest->status = REQ_DECRYPTED;
break;
}
}
}
bool anyData = true;
while (anyData)
{
anyData = false;
for (int i = 0; i < connections; ++i)
{
// synchronous writes for all remaining outstanding data (for raid, there can be a sequence of output pieces. for non-raid, one piece per connection)
// check each connection first and then all that were not yet on a connection
auto outputPiece = transferbuf.getAsyncOutputBufferPointer(i);
if (outputPiece)
{
if (!outputPiece->finalized)
{
transfer->client->tmptransfercipher.setkey(transfer->transferkey.data());
outputPiece->finalize(true, transfer->size, transfer->ctriv, &transfer->client->tmptransfercipher, &transfer->chunkmacs);
}
anyData = true;
if (fa && fa->fwrite(outputPiece->buf.datastart(), static_cast<unsigned>(outputPiece->buf.datalen()), outputPiece->pos))
{
LOG_verbose << "Sync write succeeded";
transferbuf.bufferWriteCompleted(i, true);
cachetransfer = true;
}
else
{
LOG_err << "Error caching data at: " << outputPiece->pos;
transferbuf.bufferWriteCompleted(i, false); // throws the data away so we can move on to the next one
}
}
}
}
if (cachetransfer)
{
transfer->client->transfercacheadd(transfer, nullptr);
LOG_debug << "Completed: " << transfer->progresscompleted;
}
}
transfer->slot = NULL;
if (slots_it != transfer->client->tslots.end())
{
// advance main loop iterator if deleting next in line
if (transfer->client->slotit != transfer->client->tslots.end() && *transfer->client->slotit == this)
{
transfer->client->slotit++;
}
transfer->client->tslots.erase(slots_it);
transfer->client->performanceStats.transferFinishes += 1;
}
if (pendingcmd)
{
pendingcmd->cancel();
}
if (transfer->asyncopencontext)
{
delete transfer->asyncopencontext;
transfer->asyncopencontext = NULL;
transfer->client->asyncfopens--;
}
while (connections--)
{
delete asyncIO[connections];
}
delete[] asyncIO;
}
void TransferSlot::toggleport(HttpReqXfer *req)
{
if (!memcmp(req->posturl.c_str(), "http:", 5))
{
size_t portendindex = req->posturl.find("/", 8);
size_t portstartindex = req->posturl.find(":", 8);
if (portendindex != string::npos)
{
if (portstartindex == string::npos)
{
LOG_debug << "Enabling alternative port for chunk";
req->posturl.insert(portendindex, ":8080");
}
else
{
LOG_debug << "Disabling alternative port for chunk";
req->posturl.erase(portstartindex, portendindex - portstartindex);
}
}
}
}
// abort all HTTP connections
void TransferSlot::disconnect()
{
for (int i = connections; i--;)
{
if (reqs[i])
{
reqs[i]->disconnect();
}
}
}
int64_t TransferSlot::macsmac(chunkmac_map* m)
{
return m->macsmac(transfer->transfercipher());
}
bool TransferSlot::checkTransferFinished(DBTableTransactionCommitter& committer, MegaClient* client)
{
if (transfer->progresscompleted == transfer->size)
{
if (transfer->progresscompleted)
{
transfer->currentmetamac = macsmac(&transfer->chunkmacs);
transfer->hascurrentmetamac = true;
}
// verify meta MAC
if (!transfer->progresscompleted
|| (transfer->currentmetamac == transfer->metamac))
{
client->transfercacheadd(transfer, &committer);
if (transfer->progresscompleted != progressreported)
{
progressreported = transfer->progresscompleted;
lastdata = Waiter::ds;
progress();
}
transfer->complete(committer);
}
else
{
client->sendevent(99431, "MAC verification failed", 0);
transfer->chunkmacs.clear();
transfer->failed(API_EKEY, committer);
}
return true;
}
return false;
}
bool TransferSlot::testForSlowRaidConnection(unsigned connectionNum, bool& incrementErrors)
{
if (transfer->type == GET && transferbuf.isRaid())
{
// quick early check - if we were getting data but haven't for a while
// then switch channels before we time out entirely (at the halfway-to-timeout mark)
if ((Waiter::ds - reqs[connectionNum]->lastdata) > (XFERTIMEOUT / 2))
{
LOG_warn << "Raid connection " << connectionNum << " has not received data for " << (XFERTIMEOUT / 2) << " deciseconds";
incrementErrors = true;
return true;
}
if (!transferbuf.isUnusedRaidConection(connectionNum) // connection in use
&& mReqSpeeds[connectionNum].requestElapsedDs() > 50 // enough elapsed time to be considered
&& mRaidChannelSwapsForSlowness < 2) // no more than 2 swaps due to slown connections
{
m_off_t averageOtherRate = 0;
unsigned otherCount = 0;
for (unsigned j = RAIDPARTS; j--; )
{
if (j != connectionNum && !transferbuf.isUnusedRaidConection(j))
{
if (transferbuf.isRaidConnectionProgressBlocked(j) // this one can't continue because it would get too far ahead
|| (reqs[j] && reqs[j]->status == REQ_DONE)) // this one reached end of file
{
++otherCount;
averageOtherRate += mReqSpeeds[j].lastRequestSpeed();
}
else
{
return false;
}
}
}
averageOtherRate /= otherCount ? otherCount : 1;
m_off_t thisRate = mReqSpeeds[connectionNum].lastRequestSpeed();
if (thisRate < averageOtherRate / 2 // this is less than half of avg of other connections
&& averageOtherRate > 50 * 1024 // avg is more than 50KB/s
&& thisRate < 1024 * 1024) // this is less than 1MB/s
{
LOG_warn << "Raid connection " << connectionNum
<< " is much slower than its peers, with speed " << thisRate
<< " while they are managing " << averageOtherRate;
mRaidChannelSwapsForSlowness += 1;
incrementErrors = false;
return true;
}
}
}
return false;
}
// file transfer state machine
void TransferSlot::doio(MegaClient* client, DBTableTransactionCommitter& committer)
{
CodeCounter::ScopeTimer pbt(client->performanceStats.transferslotDoio);
if (!fa || (transfer->size && transfer->progresscompleted == transfer->size)
|| (transfer->type == PUT && transfer->ultoken))
{
if (transfer->type == GET || transfer->ultoken)
{
if (fa && transfer->type == GET)
{
LOG_debug << "Verifying cached download";
transfer->currentmetamac = macsmac(&transfer->chunkmacs);
transfer->hascurrentmetamac = true;
// verify meta MAC
if (transfer->currentmetamac == transfer->metamac)
{
return transfer->complete(committer);
}
else
{
client->sendevent(99432, "MAC verification failed for cached download", 0);
transfer->chunkmacs.clear();
return transfer->failed(API_EKEY, committer);
}
}
// this is a pending completion, retry every 200 ms by default
retrybt.backoff(2);
retrying = true;
return transfer->complete(committer);
}
else
{
client->sendevent(99410, "No upload token available", 0);
return transfer->failed(API_EINTERNAL, committer);
}
}
retrying = false;
retrybt.reset(); // in case we don't delete the slot, and in case retrybt.next=1
transfer->state = TRANSFERSTATE_ACTIVE;
if (!createconnectionsonce()) // don't use connections, reqs, or asyncIO before this point.
{
return;
}
dstime backoff = 0;
m_off_t p = 0;
if (errorcount > 4)
{
LOG_warn << "Failed transfer: too many errors";
return transfer->failed(lasterror, committer);
}
// main loop over connections
for (int i = connections; i--; )
{
if (reqs[i])
{
unsigned slowestStartConnection;
if (transfer->type == GET && reqs[i]->contentlength == reqs[i]->size && transferbuf.detectSlowestRaidConnection(i, slowestStartConnection))
{
LOG_debug << "Connection " << slowestStartConnection << " is the slowest to reply, using the other 5.";
reqs[slowestStartConnection].reset();
transferbuf.resetPart(slowestStartConnection);
i = connections;
continue;
}
if (reqs[i]->status == REQ_FAILURE && reqs[i]->httpstatus == 200 && transfer->type == GET && transferbuf.isRaid()) // the request started out successfully, hence status==200 in the reply headers
{
// check if we got some data and the failure occured partway through the part chunk. If so, best not to waste it, convert to success case with less data
HttpReqDL *downloadRequest = static_cast<HttpReqDL*>(reqs[i].get());
LOG_debug << "Connection " << i << " received " << downloadRequest->bufpos << " before failing, processing data.";
if (downloadRequest->contentlength == downloadRequest->size && downloadRequest->bufpos >= RAIDSECTOR)
{
downloadRequest->bufpos -= downloadRequest->bufpos % RAIDSECTOR; // always on a raidline boundary
downloadRequest->size = unsigned(downloadRequest->bufpos);
transferbuf.transferPos(i) = downloadRequest->bufpos;
downloadRequest->status = REQ_SUCCESS;
}
}
switch (static_cast<reqstatus_t>(reqs[i]->status))
{
case REQ_INFLIGHT:
{
m_off_t delta = mReqSpeeds[i].requestProgressed(reqs[i]->transferred(client));
mTransferSpeed.calculateSpeed(delta);
p += reqs[i]->transferred(client);
assert(reqs[i]->lastdata != NEVER);
bool incrementErrors = false;
if (transfer->type == GET && transferbuf.isRaid()
&& testForSlowRaidConnection(i, incrementErrors))
{
// switch to 5 channel raid to avoid the slow/delayed connection. (or if already switched, try a different 5). If we already tried too many times then let the usual timeout occur
if (tryRaidRecoveryFromHttpGetError(i, incrementErrors))
{
LOG_warn << "Connection " << i << " is slow or stalled, trying the other 5 cloudraid connections";
reqs[i]->disconnect();
reqs[i]->status = REQ_READY;
}
}
if (EVER(reqs[i]->lastdata) && reqs[i]->lastdata > lastdata)
{
// prevent overall timeout if all channels are busy with big chunks for a while
lastdata = reqs[i]->lastdata;
}
break;
}
case REQ_SUCCESS:
{
m_off_t delta = mReqSpeeds[i].requestProgressed(reqs[i]->size);
mTransferSpeed.calculateSpeed(delta);
if (client->orderdownloadedchunks && transfer->type == GET && !transferbuf.isRaid() && transfer->progresscompleted != static_cast<HttpReqDL*>(reqs[i].get())->dlpos)
{
// postponing unsorted chunk
p += reqs[i]->size;
break;
}
lastdata = Waiter::ds;
transfer->lastaccesstime = m_time();
if (!transferbuf.isRaid())
{
LOG_debug << "Transfer request finished (" << transfer->type << ") Position: " << transferbuf.transferPos(i) << " (" << transfer->pos << ") Size: " << reqs[i]->size
<< " Completed: " << (transfer->progresscompleted + reqs[i]->size) << " of " << transfer->size << " speed " << mReqSpeeds[i].lastRequestSpeed();
}
else
{
LOG_debug << "Transfer request finished (" << transfer->type << ") " << " on connection " << i << " part pos: " << transferbuf.transferPos(i) << " of part size " << transferbuf.raidPartSize(i, transfer->size)
<< " Overall Completed: " << (transfer->progresscompleted) << " of " << transfer->size << " speed " << mReqSpeeds[i].lastRequestSpeed();
}
if (transfer->type == PUT)
{
// completed put transfers are signalled through the
// return of the upload token
if (reqs[i]->in.size())
{
if (reqs[i]->in.size() == NewNode::UPLOADTOKENLEN)
{
LOG_debug << "Upload token received";
if (!transfer->ultoken)
{
transfer->ultoken = new byte[NewNode::UPLOADTOKENLEN]();
}
bool tokenOK = true;
if (reqs[i]->in.data()[NewNode::UPLOADTOKENLEN - 1] == 1)
{
LOG_debug << "New style upload token";
memcpy(transfer->ultoken, reqs[i]->in.data(), NewNode::UPLOADTOKENLEN);
}
else
{
LOG_debug << "Old style upload token: " << reqs[i]->in;
tokenOK = (Base64::atob(reqs[i]->in.data(), transfer->ultoken, NewNode::UPLOADTOKENLEN)
== NewNode::OLDUPLOADTOKENLEN);
}
if (tokenOK)
{
errorcount = 0;
transfer->failcount = 0;
transfer->chunkmacs.finishedUploadChunks(static_cast<HttpReqUL*>(reqs[i].get())->mChunkmacs);
updatecontiguousprogress();
transfer->progresscompleted += reqs[i]->size;
memcpy(transfer->filekey, transfer->transferkey.data(), sizeof transfer->transferkey);
((int64_t*)transfer->filekey)[2] = transfer->ctriv;
((int64_t*)transfer->filekey)[3] = macsmac(&transfer->chunkmacs);
SymmCipher::xorblock(transfer->filekey + SymmCipher::KEYLENGTH, transfer->filekey);
client->transfercacheadd(transfer, &committer);
if (transfer->progresscompleted != progressreported)
{
progressreported = transfer->progresscompleted;
lastdata = Waiter::ds;
progress();
}
return transfer->complete(committer);
}
else
{
delete [] transfer->ultoken;
transfer->ultoken = NULL;
}
}
LOG_debug << "Error uploading chunk: " << reqs[i]->in;
error e = (error)atoi(reqs[i]->in.c_str());
if (e == API_EKEY)
{
client->sendevent(99429, "Integrity check failed in upload", 0);
lasterror = e;
errorcount++;
reqs[i]->status = REQ_PREPARED;
break;
}
if (e == DAEMON_EFAILED || (reqs[i]->contenttype.find("text/html") != string::npos
&& !memcmp(reqs[i]->posturl.c_str(), "http:", 5)))
{
client->usehttps = true;
client->app->notify_change_to_https();
if (e == DAEMON_EFAILED)
{
// megad returning -4 should result in restarting the transfer
client->sendevent(99440, "Retry requested by storage server", 0);
}
else
{
LOG_warn << "Invalid Content-Type detected during upload: " << reqs[i]->contenttype;
}
client->sendevent(99436, "Automatic change to HTTPS", 0);
return transfer->failed(API_EAGAIN, committer);
}
// fail with returned error
return transfer->failed(e, committer);
}
transfer->chunkmacs.finishedUploadChunks(static_cast<HttpReqUL*>(reqs[i].get())->mChunkmacs);
transfer->progresscompleted += reqs[i]->size;
updatecontiguousprogress();
if (transfer->progresscompleted == transfer->size)
{
client->sendevent(99409, "No upload token received", 0);
return transfer->failed(API_EINTERNAL, committer);
}
errorcount = 0;
transfer->failcount = 0;
client->transfercacheadd(transfer, &committer);
reqs[i]->status = REQ_READY;
}
else // GET
{
HttpReqDL *downloadRequest = static_cast<HttpReqDL*>(reqs[i].get());
if (reqs[i]->size == reqs[i]->bufpos || downloadRequest->buffer_released) // downloadRequest->buffer_released being true indicates we're retrying this asyncIO
{
if (!downloadRequest->buffer_released)
{
transferbuf.submitBuffer(i, new TransferBufferManager::FilePiece(downloadRequest->dlpos, downloadRequest->release_buf())); // resets size & bufpos. finalize() is taken care of in the transferbuf
downloadRequest->buffer_released = true;
}
auto outputPiece = transferbuf.getAsyncOutputBufferPointer(i);
if (outputPiece)
{
mRaidChannelSwapsForSlowness = 0;
bool parallelNeeded = outputPiece->finalize(false, transfer->size, transfer->ctriv, transfer->transfercipher(), &transfer->chunkmacs);
if (parallelNeeded)
{
// do full chunk (and chunk-remainder) decryption on a thread for throughput and to minimize mutex lock times.
auto req = reqs[i]; // shared_ptr for shutdown safety
auto transferkey = transfer->transferkey;
auto ctriv = transfer->ctriv;
auto filesize = transfer->size;
req->status = REQ_DECRYPTING;
client->mAsyncQueue.push([req, outputPiece, transferkey, ctriv, filesize](SymmCipher& sc)
{
sc.setkey(transferkey.data());
outputPiece->finalize(true, filesize, ctriv, &sc, nullptr);
req->status = REQ_DECRYPTED;
}, false); // not discardable: if we downloaded the data, don't waste it - decrypt and write as much as we can to file
}
else
{
reqs[i]->status = REQ_DECRYPTED;
}
}
else if (transferbuf.isRaid())
{
reqs[i]->status = REQ_READY; // this connection has retrieved a part of the file, but we don't have enough to combine yet for full file output. This connection can start fetching the next piece of that part.
}
else
{
assert(false); // non-raid, if the request succeeded then we must have a piece to write to file.
}
}
else
{
if (reqs[i]->contenttype.find("text/html") != string::npos
&& !memcmp(reqs[i]->posturl.c_str(), "http:", 5))
{
LOG_warn << "Invalid Content-Type detected during download: " << reqs[i]->contenttype;
client->usehttps = true;
client->app->notify_change_to_https();
client->sendevent(99436, "Automatic change to HTTPS", 0);
return transfer->failed(API_EAGAIN, committer);
}
client->sendevent(99430, "Invalid chunk size", 0);
LOG_warn << "Invalid chunk size: " << reqs[i]->size << " - " << reqs[i]->bufpos;
lasterror = API_EREAD;
errorcount++;
reqs[i]->status = REQ_PREPARED;
break;
}
}
break;
}
case REQ_DECRYPTED:
{
// this must return the same piece we just decrypted, since we have not asked the transferbuf to discard it yet.
auto outputPiece = transferbuf.getAsyncOutputBufferPointer(i);
if (fa->asyncavailable())
{
if (asyncIO[i])
{
LOG_warn << "Retrying failed async write";
delete asyncIO[i];
asyncIO[i] = NULL;
}
p += outputPiece->buf.datalen();
LOG_debug << "Writing data asynchronously at " << outputPiece->pos << " to " << (outputPiece->pos + outputPiece->buf.datalen());
asyncIO[i] = fa->asyncfwrite(outputPiece->buf.datastart(), static_cast<unsigned>(outputPiece->buf.datalen()), outputPiece->pos);
reqs[i]->status = REQ_ASYNCIO;
}
else
{
if (fa->fwrite(outputPiece->buf.datastart(), static_cast<unsigned>(outputPiece->buf.datalen()), outputPiece->pos))
{
LOG_verbose << "Sync write succeeded";
transferbuf.bufferWriteCompleted(i, true);
errorcount = 0;
transfer->failcount = 0;
updatecontiguousprogress();
}
else
{
LOG_err << "Error saving finished chunk";
if (!fa->retry)
{
transferbuf.bufferWriteCompleted(i, false); // discard failed data so we don't retry on slot deletion
return transfer->failed(API_EWRITE, committer);
}
lasterror = API_EWRITE;
backoff = 2;
break;
}
if (checkTransferFinished(committer, client))
{
return;
}
client->transfercacheadd(transfer, &committer);
reqs[i]->status = REQ_READY;
}
}
break;
case REQ_ASYNCIO:
if (asyncIO[i]->finished)
{
LOG_verbose << "Processing finished async fs operation";
if (!asyncIO[i]->failed)
{
if (transfer->type == PUT)
{
LOG_verbose << "Async read succeeded";
m_off_t npos = asyncIO[i]->pos + asyncIO[i]->len;
string finaltempurl = transferbuf.tempURL(i);
if (client->usealtupport && !memcmp(finaltempurl.c_str(), "http:", 5))
{
size_t index = finaltempurl.find("/", 8);
if(index != string::npos && finaltempurl.find(":", 8) == string::npos)
{
finaltempurl.insert(index, ":8080");
}
}
auto pos = asyncIO[i]->pos;
auto req = reqs[i]; // shared_ptr so no object is deleted out from under the worker
auto transferkey = transfer->transferkey;
auto ctriv = transfer->ctriv;
req->pos = pos;
req->status = REQ_ENCRYPTING;
client->mAsyncQueue.push([req, transferkey, ctriv, finaltempurl, pos, npos](SymmCipher& sc)
{
sc.setkey(transferkey.data());
req->prepare(finaltempurl.c_str(), &sc, ctriv, pos, npos);
req->status = REQ_PREPARED;
}, true); // discardable - if the transfer or client are being destroyed, we won't be sending that data.
}
else
{
LOG_verbose << "Async write succeeded";
transferbuf.bufferWriteCompleted(i, true);
errorcount = 0;
transfer->failcount = 0;
updatecontiguousprogress();
if (checkTransferFinished(committer, client))
{
return;
}
client->transfercacheadd(transfer, &committer);
reqs[i]->status = REQ_READY;
if (client->orderdownloadedchunks && !transferbuf.isRaid())
{
// Check connections again looking for postponed chunks
delete asyncIO[i];
asyncIO[i] = NULL;
i = connections;
continue;
}
}
delete asyncIO[i];
asyncIO[i] = NULL;
}
else
{
LOG_warn << "Async operation failed: " << asyncIO[i]->retry;
if (!asyncIO[i]->retry)
{
transferbuf.bufferWriteCompleted(i, false); // discard failed data so we don't retry on slot deletion
delete asyncIO[i];
asyncIO[i] = NULL;
return transfer->failed(transfer->type == PUT ? API_EREAD : API_EWRITE, committer);
}
// retry shortly
if (transfer->type == PUT)
{
lasterror = API_EREAD;
reqs[i]->status = REQ_READY;
}
else
{
lasterror = API_EWRITE;
reqs[i]->status = REQ_SUCCESS;
}
backoff = 2;
}
}
else if (transfer->type == GET)
{
p += asyncIO[i]->len;
}
break;
case REQ_FAILURE:
LOG_warn << "Failed chunk. HTTP status: " << reqs[i]->httpstatus << " on channel " << i;
if (reqs[i]->httpstatus && reqs[i]->contenttype.find("text/html") != string::npos
&& !memcmp(reqs[i]->posturl.c_str(), "http:", 5))
{
LOG_warn << "Invalid Content-Type detected on failed chunk: " << reqs[i]->contenttype;
client->usehttps = true;
client->app->notify_change_to_https();
client->sendevent(99436, "Automatic change to HTTPS", 0);
return transfer->failed(API_EAGAIN, committer);
}
if (reqs[i]->httpstatus == 509)
{
if (reqs[i]->timeleft < 0)
{
client->sendevent(99408, "Overquota without timeleft", 0);
}
LOG_warn << "Bandwidth overquota from storage server";
if (reqs[i]->timeleft > 0)
{
backoff = dstime(reqs[i]->timeleft * 10);
}
else
{
// default retry intervals
backoff = MegaClient::DEFAULT_BW_OVERQUOTA_BACKOFF_SECS * 10;
}
return transfer->failed(API_EOVERQUOTA, committer, backoff);
}
else if (reqs[i]->httpstatus == 429)
{
// too many requests - back off a bit (may be added serverside at some point. Added here 202020623)
backoff = 5;
reqs[i]->status = REQ_PREPARED;
}
else if (reqs[i]->httpstatus == 503 && !transferbuf.isRaid())
{
// for non-raid, if a file gets a 503 then back off as it may become available shortly
backoff = 50;
reqs[i]->status = REQ_PREPARED;
}
else if (reqs[i]->httpstatus == 403 || reqs[i]->httpstatus == 404 || (reqs[i]->httpstatus == 503 && transferbuf.isRaid()))
{
// - 404 means "malformed or expired URL" - can be immediately fixed by getting a fresh one from the API
// - 503 means "the API gave you good information, but I don't have the file" - cannot be fixed (at least not immediately) by getting a fresh URL
// for raid parts and 503, it's appropriate to try another raid source
if (!tryRaidRecoveryFromHttpGetError(i, true))
{
return transfer->failed(API_EAGAIN, committer);
}
}
else if (reqs[i]->httpstatus == 0 && tryRaidRecoveryFromHttpGetError(i, true))
{
// status 0 indicates network error or timeout; no headers recevied.
// tryRaidRecoveryFromHttpGetError has switched to loading a different part instead of this one.
}
else
{
if (!failure)
{
failure = true;
bool changeport = false;
if (transfer->type == GET && client->autodownport && !memcmp(transferbuf.tempURL(i).c_str(), "http:", 5))
{
LOG_debug << "Automatically changing download port";
client->usealtdownport = !client->usealtdownport;
changeport = true;
}
else if (transfer->type == PUT && client->autoupport && !memcmp(transferbuf.tempURL(i).c_str(), "http:", 5))
{
LOG_debug << "Automatically changing upload port";
client->usealtupport = !client->usealtupport;
changeport = true;
}