You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

74 lines
2.1 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. #include "tile_downloader.h"
  2. MemoryStruct::MemoryStruct(): size(0), memory(NULL){
  3. }
  4. MemoryStruct::~MemoryStruct(){
  5. free(memory);
  6. }
  7. int MemoryStruct::append(void *contents, int len){
  8. memory = (char *)realloc(memory, size + len);
  9. if(memory == NULL) {
  10. /* out of memory! */
  11. fprintf(stderr, "not enough memory (realloc returned NULL)\n");
  12. exit(-1);
  13. }
  14. memcpy(&memory[size], contents, len);
  15. size += len;
  16. return len;
  17. }
  18. size_t MemoryStruct::write_callback(void *contents, size_t size, size_t nmemb, void *userp){
  19. struct MemoryStruct *mem = (struct MemoryStruct *)userp;
  20. return mem->append(contents, size * nmemb);
  21. }
  22. TileDownloader::TileDownloader(): multi_handle(curl_multi_init()){
  23. }
  24. int TileDownloader::active(){
  25. return transfers.size();
  26. }
  27. void TileDownloader::queue(Tile *tile){
  28. CURL *curl = curl_easy_init();
  29. transfers.push_back(new Transfer(curl, tile));
  30. curl_multi_add_handle(multi_handle, curl);
  31. tile->queue();
  32. }
  33. int TileDownloader::work(){
  34. int msgs_left;
  35. CURLMsg *msg;
  36. curl_multi_perform(multi_handle, &still_running);
  37. while((msg = curl_multi_info_read(multi_handle, &msgs_left))){
  38. if(msg->msg == CURLMSG_DONE){
  39. for(std::list<Transfer *>::iterator it = transfers.begin(); it != transfers.end(); ++it){
  40. if((*it)->curl == msg->easy_handle){
  41. if(msg->data.result){
  42. fprintf(stderr, "Error loading '%s': %s\n", (*it)->tile->url().c_str(), curl_easy_strerror(msg->data.result));
  43. }else{
  44. (*it)->finish();
  45. }
  46. curl_multi_remove_handle(multi_handle, msg->easy_handle);
  47. curl_easy_cleanup(msg->easy_handle);
  48. transfers.erase(it);
  49. delete *it;
  50. break;
  51. }
  52. }
  53. }
  54. }
  55. return still_running;
  56. }
  57. TileDownloader::Transfer::Transfer(CURL *curl, Tile *tile): curl(curl), tile(tile){
  58. curl_easy_setopt(curl, CURLOPT_USERAGENT, "sdlmap/1.0");
  59. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  60. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, MemoryStruct::write_callback);
  61. curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);
  62. curl_easy_setopt(curl, CURLOPT_URL, tile->url().c_str());
  63. }
  64. void TileDownloader::Transfer::finish(){
  65. tile->load(chunk.memory, chunk.size);
  66. }