/
netutils.cpp
1392 lines (1261 loc) · 38.6 KB
/
netutils.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
/**************************************************************************
Lightspark, a free flash player implementation
Copyright (C) 2010-2013 Alessandro Pignotti (a.pignotti@sssup.it)
Copyright (C) 2010-2012 Timon Van Overveldt (timonvo@gmail.com)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
**************************************************************************/
#include "backends/security.h"
#include "scripting/abc.h"
#include "swf.h"
#include "backends/config.h"
#include "backends/netutils.h"
#include "backends/rtmputils.h"
#include "compat.h"
#include <string>
#include <algorithm>
#include <cctype>
#include <iostream>
#include <fstream>
#ifdef ENABLE_CURL
#include <curl/curl.h>
#endif
using namespace lightspark;
/**
* \brief Download manager constructor
*
* Can only be called from within a derived class
*/
DownloadManager::DownloadManager()
{
}
/**
* \brief Download manager destructor
*/
DownloadManager::~DownloadManager()
{
}
/**
* \brief Stops all the currently running downloaders
*/
void DownloadManager::stopAll()
{
Mutex::Lock l(mutex);
std::list<Downloader*>::iterator it=downloaders.begin();
for(;it!=downloaders.end();++it)
(*it)->stop();
}
/**
* \brief Destroyes all the pending downloads, must be called in the destructor of each derived class
*
* Traverses the list of active downloaders, calling \c stop() and \c destroy() on all of them.
* If the downloader is already destroyed, destroy() won't do anything (no double delete).
* Waits for the mutex before proceeding.
* \see Downloader::stop()
* \see Downloader::destroy()
*/
void DownloadManager::cleanUp()
{
Mutex::Lock l(mutex);
while(!downloaders.empty())
{
std::list<Downloader*>::iterator it=downloaders.begin();
//cleanUp should only happen after stopAll has been called
assert((*it)->hasFinished());
l.release();
destroy(*it);
l.acquire();
}
}
/**
* \brief Destroy a Downloader.
*
* Destroy a given \c Downloader.
* \param downloader A pointer to the \c Downloader to be destroyed.
* \see DownloadManager::download()
*/
void StandaloneDownloadManager::destroy(Downloader* downloader)
{
//If the downloader was still in the active-downloader list, delete it
if(removeDownloader(downloader))
{
downloader->waitForTermination();
ThreadedDownloader* thd=dynamic_cast<ThreadedDownloader*>(downloader);
if(thd)
thd->waitFencing();
delete downloader;
}
}
/**
* \brief Add a Downloader to the active downloads list
*
* Waits for the mutex at start and releases the mutex when finished.
*/
void DownloadManager::addDownloader(Downloader* downloader)
{
Mutex::Lock l(mutex);
downloaders.push_back(downloader);
}
/**
* \brief Remove a Downloader from the active downloads list
*
* Waits for the mutex at start and releases the mutex when finished.
*/
bool DownloadManager::removeDownloader(Downloader* downloader)
{
Mutex::Lock l(mutex);
for(std::list<Downloader*>::iterator it=downloaders.begin(); it!=downloaders.end(); ++it)
{
if((*it) == downloader)
{
downloaders.erase(it);
return true;
}
}
return false;
}
/**
* \brief Standalone download manager constructor.
*
* The standalone download manager produces \c ThreadedDownloader-type \c Downloaders.
* It should only be used in the standalone version of LS.
*/
StandaloneDownloadManager::StandaloneDownloadManager()
{
type = STANDALONE;
}
StandaloneDownloadManager::~StandaloneDownloadManager()
{
cleanUp();
}
/**
* \brief Create a Downloader for an URL.
*
* Returns a pointer to a newly created \c Downloader for the given URL.
* \param[in] url The URL (as a \c URLInfo) the \c Downloader is requested for
* \param[in] cached Whether or not to disk-cache the download (default=false)
* \return A pointer to a newly created \c Downloader for the given URL.
* \see DownloadManager::destroy()
*/
Downloader* StandaloneDownloadManager::download(const URLInfo& url, bool cached, ILoadable* owner)
{
LOG(LOG_INFO, _("NET: STANDALONE: DownloadManager::download '") << url.getParsedURL()
<< "'" << (cached ? _(" - cached") : ""));
ThreadedDownloader* downloader;
if(url.getProtocol() == "file")
{
LOG(LOG_INFO, _("NET: STANDALONE: DownloadManager: local file"));
downloader=new LocalDownloader(url.getPath(), cached, owner);
}
else if(url.getProtocol().substr(0, 4) == "rtmp")
{
LOG(LOG_INFO, _("NET: STANDALONE: DownloadManager: RTMP stream"));
downloader=new RTMPDownloader(url.getParsedURL(), url.getStream(), owner);
}
else
{
LOG(LOG_INFO, _("NET: STANDALONE: DownloadManager: remote file"));
downloader=new CurlDownloader(url.getParsedURL(), cached, owner);
}
downloader->enableFencingWaiting();
addDownloader(downloader);
getSys()->addJob(downloader);
return downloader;
}
/**
* \brief Create a Downloader for an URL and send data to the host
*
* Returns a pointer to a newly created \c Downloader for the given URL.
* \param[in] url The URL (as a \c URLInfo) the \c Downloader is requested for
* \param[in] data The binary data to send to the host
* \param[in] headers Request headers in the full form, f.e. "Content-Type: ..."
* \return A pointer to a newly created \c Downloader for the given URL.
* \see DownloadManager::destroy()
*/
Downloader* StandaloneDownloadManager::downloadWithData(const URLInfo& url, const std::vector<uint8_t>& data,
const std::list<tiny_string>& headers, ILoadable* owner)
{
LOG(LOG_INFO, _("NET: STANDALONE: DownloadManager::downloadWithData '") << url.getParsedURL());
ThreadedDownloader* downloader;
if(url.getProtocol() == "file")
{
LOG(LOG_INFO, _("NET: STANDALONE: DownloadManager: local file - Ignoring data field"));
downloader=new LocalDownloader(url.getPath(), false, owner);
}
else if(url.getProtocol() == "rtmpe")
throw RunTimeException("RTMPE does not support additional data");
else
{
LOG(LOG_INFO, _("NET: STANDALONE: DownloadManager: remote file"));
downloader=new CurlDownloader(url.getParsedURL(), data, headers, owner);
}
downloader->enableFencingWaiting();
addDownloader(downloader);
getSys()->addJob(downloader);
return downloader;
}
/**
* \brief Downloader constructor.
*
* Constructor for the Downloader class. Can only be called from derived classes.
* \param[in] _url The URL for the Downloader.
* \param[in] _cached Whether or not to cache this download.
*/
Downloader::Downloader(const tiny_string& _url, bool _cached, ILoadable* o):
cacheOpened(0),dataAvailable(0),terminated(0),hasTerminated(false),cacheHasOpened(false), //LOCKING
waitingForCache(false),waitingForData(false),waitingForTermination(false), //STATUS
forceStop(true),failed(false),finished(false), //FLAGS
url(_url),originalURL(url), //PROPERTIES
buffer(NULL),stableBuffer(NULL), //BUFFERING
owner(o), //PROGRESS
cachePos(0),cacheSize(0),keepCache(false),cached(_cached), //CACHING
redirected(false),requestStatus(0), //HTTP REDIR, STATUS & HEADERS
length(0),receivedLength(0) //DOWNLOADED DATA
{
setg(NULL,NULL,NULL);
}
/**
* \brief Downloader constructor.
*
* Constructor for the Downloader class. Can only be called from derived classes.
* \param[in] _url The URL for the Downloader.
* \param[in] data Additional data to send to the host
*/
Downloader::Downloader(const tiny_string& _url, const std::vector<uint8_t>& _data, const std::list<tiny_string>& h, ILoadable* o):
cacheOpened(0),dataAvailable(0),terminated(0),hasTerminated(false),cacheHasOpened(false), //LOCKING
waitingForCache(false),waitingForData(false),waitingForTermination(false), //STATUS
forceStop(true),failed(false),finished(false), //FLAGS
url(_url),originalURL(url), //PROPERTIES
buffer(NULL),stableBuffer(NULL), //BUFFERING
owner(o), //PROGRESS
cachePos(0),cacheSize(0),keepCache(false),cached(false), //CACHING
redirected(false),requestStatus(0),requestHeaders(h),data(_data),//HTTP REDIR, STATUS & HEADERS
length(0),receivedLength(0) //DOWNLOADED DATA
{
setg(NULL,NULL,NULL);
}
/**
* \brief Downloader destructor.
*
* Destructor for the Downloader class. Can only be called from derived/friend classes (DownloadManager)
* Calls \c waitForTermination() and waits for the mutex before proceeding.
* \see Downloader::waitForTermination()
*/
Downloader::~Downloader()
{
waitForTermination();
Mutex::Lock l(mutex);
if(cached)
{
if(cache.is_open())
cache.close();
if(!keepCache && cacheFilename != "")
unlink(cacheFilename.raw_buf());
}
if(buffer != NULL)
{
free(buffer);
}
if(stableBuffer != NULL && stableBuffer!=buffer)
{
free(stableBuffer);
}
}
/**
* \brief Called by the streambuf API
*
* Called by the streambuf API when there is no more data to read.
* Waits for the mutex at start and releases the mutex when finished.
* \throw RunTimeException Cache file could not be read
*/
Downloader::int_type Downloader::underflow()
{
Mutex::Lock l(mutex);
//Let's see if the other buffer contains new data
syncBuffers();
if(egptr()-gptr()>0)
{
//There is data already
return *(uint8_t*)gptr();
}
const unsigned int startOffset=getOffset();
const unsigned int startReceivedLength=receivedLength;
assert(startOffset<=startReceivedLength);
//If we have read all available data
if(startReceivedLength==startOffset)
{
//The download has failed or has finished
if(failed || finished)
return EOF;
//We haven't reached the end of the download, more bytes should follow
else
{
waitForData_locked();
syncBuffers();
//Check if we haven't failed or finished (and there wasn't any new data)
if(failed || (finished && startReceivedLength==receivedLength))
return EOF;
}
}
//We should have an initialized buffer here since there is some data
assert_and_throw(buffer != NULL);
//Temporary pointers to new streambuf read positions
char* begin;
char* cur;
char* end;
//Index in the buffer pointing to the data to be returned
uint32_t index;
if(cached)
{
waitForCache();
size_t newCacheSize = receivedLength-(cachePos+cacheSize);
if(newCacheSize > cacheMaxSize)
newCacheSize = cacheMaxSize;
//Move the start of our new window to the end of our last window
cachePos = cachePos+cacheSize;
cacheSize = newCacheSize;
//Seek to the start of our new window
cache.seekg(cachePos);
//Read into our buffer window
cache.read((char*)stableBuffer, cacheSize);
if(cache.fail())
{
throw RunTimeException(_("Downloader::underflow: reading from cache file failed"));
}
begin=(char*)stableBuffer;
cur=(char*)stableBuffer;
end=(char*)stableBuffer+cacheSize;
index=0;
}
else
{
begin=(char*)stableBuffer;
cur=(char*)stableBuffer+startOffset;
end=(char*)stableBuffer+receivedLength;
index=startOffset;
}
//If we've failed, don't bother any more
if(failed)
return EOF;
//Set our new iterators in the buffer (begin, cursor, end)
setg(begin, cur, end);
//Cast to unsigned, otherwise 0xff would become eof
return (unsigned char)stableBuffer[index];
}
/**
* Internal function to synchronize oldBuffer and buffer
*
* \pre Must be called from a function called by the streambuf API
*/
void Downloader::syncBuffers()
{
if(stableBuffer!=buffer)
{
//The buffer have been changed
free(stableBuffer);
stableBuffer=buffer;
//Remember the relative positions of the input pointers
intptr_t curPos = (intptr_t) (gptr()-eback());
intptr_t curLen = (intptr_t) (egptr()-eback());
//Do some pointer arithmetic to point the input pointers to the right places in the new buffer
setg((char*)stableBuffer,(char*)(stableBuffer+curPos),(char*)(stableBuffer+curLen));
}
}
/**
* \brief Called by the streambuf API
*
* Called by the streambuf API to seek to an absolute position
* Mutex must be locked on entry.
* \throw RunTimeException Cache file could not be read
*/
Downloader::pos_type Downloader::seekpos(pos_type pos, std::ios_base::openmode mode)
{
assert_and_throw(mode==std::ios_base::in);
assert_and_throw(buffer && stableBuffer);
syncBuffers();
// read from stream until we have enough data
uint32_t tmplen = receivedLength;
while (!hasTerminated && pos > receivedLength)
{
waitForData_locked();
syncBuffers();
if (tmplen == receivedLength)
break; // no new data read
tmplen = receivedLength;
}
if(cached)
{
waitForCache();
//The requested position is inside our current window
if(pos >= cachePos && pos <= cachePos+cacheSize)
{
//Just move our cursor to the correct position in our window
setg((char*)stableBuffer, (char*)stableBuffer+pos-cachePos, (char*)stableBuffer+cacheSize);
}
//The requested position is outside our current window
else if(pos <= receivedLength)
{
cachePos = pos;
cacheSize = receivedLength-pos;
if(cacheSize > cacheMaxSize)
cacheSize = cacheMaxSize;
//Seek to the requested position
cache.seekg(cachePos);
//Read into our window
cache.read((char*)stableBuffer, cacheSize);
if(cache.fail())
throw RunTimeException(_("Downloader::seekpos: reading from cache file failed"));
//Our window starts at position pos
setg((char*) stableBuffer, (char*) stableBuffer, ((char*) stableBuffer)+cacheSize);
}
//The requested position is bigger then our current amount of available data
else if(pos > receivedLength)
return -1;
}
else
{
//The requested position is valid
if(pos <= receivedLength)
setg((char*)stableBuffer,(char*)stableBuffer+pos,(char*)stableBuffer+receivedLength);
//The requested position is bigger then our current amount of available data
else
return -1;
}
return pos;
}
/**
* \brief Called by the streambuf API
*
* Called by the streambuf API to seek to a relative position
* Waits for the mutex at start and releases the mutex when finished.
*/
Downloader::pos_type Downloader::seekoff(off_type off, std::ios_base::seekdir dir, std::ios_base::openmode mode)
{
assert_and_throw(mode==std::ios_base::in);
assert_and_throw(buffer != NULL);
Mutex::Lock l(mutex);
if (off != 0)
{
switch (dir)
{
case std::ios_base::beg:
seekpos(off,mode);
break;
case std::ios_base::cur:
{
pos_type tmp = getOffset();
seekpos(tmp+off,mode);
break;
}
case std::ios_base::end:
l.release();
waitForTermination();
l.acquire();
if (finished)
seekpos(length+off,mode);
break;
default:
break;
}
}
return getOffset();
}
/**
* \brief Get the position of the read cursor in the (virtual) downloaded data
*
* Get the position of the read cursor in the (virtual) downloaded data.
* If downloading to memory this method returns the position of the read cursor in the buffer.
* If downloading to a cache file, this method returns the position of the read cursor in the buffer
* + the position of the buffer window into the cache file.
*/
Downloader::pos_type Downloader::getOffset() const
{
pos_type ret = gptr()-eback();
if(cached)
ret+=cachePos;
return ret;
}
/**
* \brief Marks the downloader as failed
*
* Sets the \c failed and finished flag to \c true, sets the final length and
* signals \c dataAvailable if it is being waited for.
* It also signals \c terminated to mark the end of the download.
* A download should finish be either calling \c setFailed() or \c setFinished(), not both.
* \post \c failed == \c true & \c finished == \c true
* \post \c length == \c receivedLength
* \post Signals \c dataAvailable if it is being waited for (\c waitingForData == \c true).
* \post \c waitingForTermination == \c false
* \post Signals \c terminated
*/
void Downloader::setFailed()
{
failed=true;
finished = true;
//Set the final length
length = receivedLength;
//If we are waiting for data to become available, signal dataAvailable
if(waitingForData)
{
waitingForData = false;
dataAvailable.signal();
}
waitingForTermination = false;
terminated.signal();
}
/**
* \brief Marks the downloader as finished
*
* Marks the downloader as finished, sets the final length and
* signals \c dataAvailable if it is being waited for.
* It also signals \c terminated to mark the end of the download.
* A download should finish be either calling \c setFailed() or \c setFinished(), not both.
* \post \c finished == \ctrue
* \post \c length == \c receivedLength
* \post Signals \c dataAvailable if it is being waited for (\c waitingForData == true).
* \post \c waitingForTermination == \c false
* \post Signals \c terminated
*/
void Downloader::setFinished()
{
finished=true;
//Set the final length
length = receivedLength;
//If we are waiting for data to become available, signal dataAvailable
if(waitingForData)
{
waitingForData = false;
dataAvailable.signal();
}
waitingForTermination = false;
terminated.signal();
}
/**
* \brief (Re)allocates the buffer
*
* (Re)allocates the buffer to a given size
* Waits for mutex at start and releases mutex when finished.
* \post \c buffer is (re)allocated
* mutex must be locked on entry
*/
void Downloader::allocateBuffer(size_t size)
{
//Create buffer
if(buffer == NULL)
{
buffer = (uint8_t*) calloc(size, sizeof(uint8_t));
stableBuffer = buffer;
setg((char*)buffer,(char*)buffer,(char*)buffer);
}
//If the buffer already exists, reallocate
else
{
assert(!cached);
intptr_t curLen = receivedLength;
//We have to extend the buffer, so create a new one
if(stableBuffer!=buffer)
{
//We're already filling a different buffer from the one used to read
//Extend it!
buffer = (uint8_t*)realloc(buffer,size);
}
else
{
//Create a different buffer
buffer = (uint8_t*) calloc(size, sizeof(uint8_t));
//Copy the stableBuffer into this
memcpy(buffer,stableBuffer,curLen);
}
//Synchronization of the buffers will be done at the first chance
}
}
/**
* \brief Creates & opens a temporary cache file
*
* Creates a temporary cache file in /tmp and calls \c openExistingCache() with that file.
* Waits for mutex at start and releases mutex when finished.
* \throw RunTimeException Temporary file could not be created
* \throw RunTimeException Called when the downloader isn't cached or when the cache is already open
* \see Downloader::openExistingCache()
* mutex must be hold prior calling
*/
void Downloader::openCache()
{
//Only act if the downloader is cached and the cache hasn't been opened yet
if(cached && !cache.is_open())
{
//Create a temporary file(name)
std::string cacheFilenameS = Config::getConfig()->getCacheDirectory() + "/" + Config::getConfig()->getCachePrefix() + "XXXXXX";
char* cacheFilenameC = g_newa(char,cacheFilenameS.length()+1);
strncpy(cacheFilenameC, cacheFilenameS.c_str(), cacheFilenameS.length());
cacheFilenameC[cacheFilenameS.length()] = '\0';
//char cacheFilenameC[30] = "/tmp/lightsparkdownloadXXXXXX";
//strcpy(cacheFilenameC, "/tmp/lightsparkdownloadXXXXXX");
int fd = g_mkstemp(cacheFilenameC);
if(fd == -1)
throw RunTimeException(_("Downloader::openCache: cannot create temporary file"));
//We are using fstream to read/write to the cache, so we don't need this FD
close(fd);
//Let the openExistingCache function handle the rest
openExistingCache(tiny_string(cacheFilenameC, true));
}
else
throw RunTimeException(_("Downloader::openCache: downloader isn't cached or called twice"));
}
/**
* \brief Opens an existing cache file
*
* Opens an existing cache file, allocates the buffer and signals \c cacheOpened.
* Waits for mutex at start and releases mutex when finished.
* \post \c cacheFilename is set
* \post \c cache file is opened
* \post \c buffer is initialized
* \post \c cacheOpened is signalled
* \throw RunTimeException File could not be opened
* \throw RunTimeException Called when the downloader isn't cached or when the cache is already open
* \see Downloader::allocateBuffer()
* mutex must be hold on entering
*/
void Downloader::openExistingCache(tiny_string filename)
{
//Only act if the downloader is cached and the cache hasn't been opened yet
if(cached && !cache.is_open())
{
//Save the filename
cacheFilename = filename;
//Open the cache file
cache.open(cacheFilename.raw_buf(), std::fstream::binary | std::fstream::in | std::fstream::out);
if(!cache.is_open())
throw RunTimeException(_("Downloader::openCache: cannot open temporary cache file"));
allocateBuffer(cacheMaxSize);
LOG(LOG_INFO, _("NET: Downloading to cache file: ") << cacheFilename);
cacheOpened.signal();
}
else
throw RunTimeException(_("Downloader::openCache: downloader isn't cached or called twice"));
}
/**
* \brief Set the expected length of the download
*
* Sets the expected length of the download.
* Can be called multiple times if the length isn't known up front (reallocating the buffer on the fly).
* Waits for mutex at start and releases mutex when finished.
* \post \c buffer is (re)allocated
* mutex must be hold prior calling
*/
void Downloader::setLength(uint32_t _length)
{
//Set the length
length=_length;
//The first call to this function should open the cache
if(cached)
{
if(!cache.is_open())
openCache();
}
else
{
if(buffer == NULL)
LOG(LOG_INFO, _("NET: Downloading to memory"));
allocateBuffer(length);
}
notifyOwnerAboutBytesTotal();
}
/**
* \brief Appends data to the buffer
*
* Appends a given amount of received data to the buffer/cache.
* This method will grow the expected length of the download on-the-fly as needed.
* So when \c length == 0 this call will call \c setLength(added)
* Waits for mutex at start and releases mutex when finished.
* \post \c buffer/cache contains the added data
* \post \c length = \c receivedLength + \c added
* \see Downloader::setLength()
*/
void Downloader::append(uint8_t* buf, uint32_t added)
{
if(added==0)
return;
Mutex::Lock l(mutex);
//If the added data would overflow the buffer, grow it
if((receivedLength+added)>length)
{
uint32_t newLength;
assert(length>=receivedLength);
//If reallocating the buffer ask for a minimum amount of space
if((receivedLength+added)-length > bufferMinGrowth)
newLength = receivedLength + added;
else
newLength = length + bufferMinGrowth;
assert(newLength>=receivedLength+added);
setLength(newLength);
}
if(cached)
{
//Seek to where we last wrote data
cache.seekp(receivedLength);
cache.write((char*) buf, added);
}
else
memcpy(buffer+receivedLength, buf, added);
receivedLength += added;
if(waitingForData)
{
waitingForData = false;
dataAvailable.signal();
}
notifyOwnerAboutBytesLoaded();
}
/**
* \brief Parse a string of multiple headers.
*
* Parses a string of multiple headers.
* Header lines are expected to be seperated by \n
* Calls \c parseHeader on every individual header.
* \see Downloader::parseHeader()
*/
void Downloader::parseHeaders(const char* _headers, bool _setLength)
{
if(_headers == NULL)
return;
std::string headersStr(_headers);
size_t cursor = 0;
size_t newLinePos = headersStr.find("\n");
while(newLinePos != std::string::npos)
{
if(headersStr[cursor] == '\n')
cursor++;
parseHeader(headersStr.substr(cursor, newLinePos-cursor), _setLength);
cursor = newLinePos;
newLinePos = headersStr.find("\n", cursor+1);
}
}
/**
* \brief Parse a string containing a single header.
*
* Parse a string containing a single header.
* The header line is not expected to contain a newline character.
* Waits for mutex at start and releases mutex when finished.
*/
void Downloader::parseHeader(std::string header, bool _setLength)
{
Mutex::Lock l(mutex);
if(header.substr(0, 9) == "HTTP/1.1 " || header.substr(0, 9) == "HTTP/1.0 ")
{
std::string status = header.substr(9, 3);
requestStatus = atoi(status.c_str());
//HTTP error or server error or proxy error, let's fail
//TODO: shouldn't we fetch the data anyway
if(getRequestStatus()/100 == 4 ||
getRequestStatus()/100 == 5 ||
getRequestStatus()/100 == 6)
{
setFailed();
}
else if(getRequestStatus()/100 == 3) {;} //HTTP redirect
else if(getRequestStatus()/100 == 2) {;} //HTTP OK
}
else
{
std::string headerName;
std::string headerValue;
size_t colonPos;
colonPos = header.find(":");
if(colonPos != std::string::npos)
{
headerName = header.substr(0, colonPos);
if(header[colonPos+1] == ' ')
headerValue = header.substr(colonPos+2, header.length()-colonPos-1);
else
headerValue = header.substr(colonPos+1, header.length()-colonPos);
std::transform(headerName.begin(), headerName.end(), headerName.begin(), ::tolower);
//std::transform(headerValue.begin(), headerValue.end(), headerValue.begin(), ::tolower);
headers.insert(std::make_pair(tiny_string(headerName), tiny_string(headerValue)));
//Set the new real URL when we are being redirected
if(getRequestStatus()/100 == 3 && headerName == "location")
{
LOG(LOG_INFO, _("NET: redirect detected"));
setRedirected(URLInfo(url).goToURL(tiny_string(headerValue)).getParsedURL());
}
if(headerName == "content-length")
{
//Now read the length and allocate the byteArray
//Only read the length when we're not redirecting
if(getRequestStatus()/100 != 3)
{
setLength(atoi(headerValue.c_str()));
return;
}
}
}
}
}
/**
* \brief Forces the download to stop
*
* Sets the \c failed and finished flag to \c true, sets the final length and signals \c dataAvailable
* \post \c failed == true & finished == true
* \post \c length == receivedLength
* \post \c dataAvailable is signalled
* \post \c waitingForTermination == \c false
* \post Signals \c terminated
*/
void Downloader::stop()
{
failed = true;
finished = true;
length = receivedLength;
waitingForData = false;
dataAvailable.signal();
waitingForTermination = false;
terminated.signal();
}
/**
* \brief Wait for the cache file to be opened
*
* If \c !cacheHasOpened: wait for the \c cacheOpened signal and set \c cacheHasOpened to \c true
* Waits for the mutex at start and releases the mutex when finished.
* \post \c cacheOpened signals has been handled
* \post \c cacheHasOpened = true
* mutex must be locked on entry
*/
void Downloader::waitForCache()
{
if(!cacheHasOpened)
{
waitingForCache = true;
mutex.unlock();
cacheOpened.wait();
mutex.lock();
cacheHasOpened = true;
}
}
/**
* \brief Wait for data to become available
*
* Wait for data to become available.
* Waits for the mutex at start and releases the mutex when finished.
* \post \c dataAvailable signal has been handled
*/
void Downloader::waitForData_locked()
{
waitingForData = true;
mutex.unlock();
dataAvailable.wait();
mutex.lock();
}
/**
* \brief Wait for termination of the downloader
*
* If \c getSys()->isShuttingDown(), calls \c setFailed() and returns.
* Otherwise if \c !hasTerminated: wait for the \c terminated signal and set \c hasTerminated to \c true
* Waits for the mutex at start and releases the mutex when finished.
* \post \c terminated signal has been handled
* \post \c hasTerminated = true
*/
void Downloader::waitForTermination()
{
Mutex::Lock l(mutex);
if(getSys()->isShuttingDown())
{
setFailed();
return;
}
if(!hasTerminated)
{
waitingForTermination = true;
l.release();
terminated.wait();
l.acquire();
hasTerminated = true;
}
}
void Downloader::notifyOwnerAboutBytesTotal() const
{
if(owner)
owner->setBytesTotal(length);
}
void Downloader::notifyOwnerAboutBytesLoaded() const
{
if(owner)
owner->setBytesLoaded(receivedLength);
}
void ThreadedDownloader::enableFencingWaiting()
{
RELEASE_WRITE(fenceState,true);
}
/**
* \brief The jobFence for ThreadedDownloader.
*
* This is the very last thing \c ThreadPool does with the \c ThreadedDownloader.
* \post The \c fenceState is set to false
*/
void ThreadedDownloader::jobFence()
{
RELEASE_WRITE(fenceState,false);
}