Fixed corrupt image download via proxy server
[platform/core/uifw/dali-adaptor.git] / dali / internal / imaging / common / file-download.cpp
1 /*
2  * Copyright (c) 2022 Samsung Electronics Co., Ltd.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  */
17
18 // HEADER
19 #include <dali/internal/imaging/common/file-download.h>
20
21 // EXTERNAL INCLUDES
22 #include <curl/curl.h>
23 #include <dali/integration-api/debug.h>
24 #include <pthread.h>
25 #include <cstdlib>
26 #include <cstring>
27
28 // INTERNAL INCLUDES
29 #include <dali/internal/system/common/file-writer.h>
30
31 using namespace Dali::Integration;
32
33 namespace Dali
34 {
35 namespace TizenPlatform
36 {
37 namespace // unnamed namespace
38 {
39 inline void LogCurlResult(CURLcode result, char* errorBuffer, std::string url, std::string prefix)
40 {
41   if(result != CURLE_OK)
42   {
43     if(errorBuffer != nullptr)
44     {
45       DALI_LOG_ERROR("%s \"%s\" with error code %d\n", prefix.c_str(), url.c_str(), result);
46     }
47     else
48     {
49       DALI_LOG_ERROR("$s \"%s\" with error code %d (%s)\n", prefix.c_str(), url.c_str(), result, errorBuffer);
50     }
51   }
52 }
53
54 const int  CONNECTION_TIMEOUT_SECONDS(30L);
55 const int  TIMEOUT_SECONDS(120L);
56 const long VERBOSE_MODE              = 0L; // 0 == off, 1 == on
57 const long CLOSE_CONNECTION_ON_ERROR = 1L; // 0 == off, 1 == on
58 const long EXCLUDE_HEADER            = 0L;
59 const long INCLUDE_HEADER            = 1L;
60 const long INCLUDE_BODY              = 0L;
61 const long EXCLUDE_BODY              = 1L;
62
63 /**
64  * Curl library environment. Direct initialize ensures it's constructed before adaptor
65  * or application creates any threads.
66  */
67 static Dali::TizenPlatform::Network::CurlEnvironment gCurlEnvironment;
68
69 void ConfigureCurlOptions(CURL* curlHandle, const std::string& url)
70 {
71   curl_easy_setopt(curlHandle, CURLOPT_URL, url.c_str());
72   curl_easy_setopt(curlHandle, CURLOPT_VERBOSE, VERBOSE_MODE);
73
74   // CURLOPT_FAILONERROR is not fail-safe especially when authentication is involved ( see manual )
75   // Removed CURLOPT_FAILONERROR option
76   curl_easy_setopt(curlHandle, CURLOPT_CONNECTTIMEOUT, CONNECTION_TIMEOUT_SECONDS);
77   curl_easy_setopt(curlHandle, CURLOPT_TIMEOUT, TIMEOUT_SECONDS);
78   curl_easy_setopt(curlHandle, CURLOPT_HEADER, INCLUDE_HEADER);
79   curl_easy_setopt(curlHandle, CURLOPT_NOBODY, EXCLUDE_BODY);
80   curl_easy_setopt(curlHandle, CURLOPT_NOSIGNAL, 1L);
81   curl_easy_setopt(curlHandle, CURLOPT_FOLLOWLOCATION, 1L);
82   curl_easy_setopt(curlHandle, CURLOPT_MAXREDIRS, 5L);
83
84   // If the proxy variable is set, ensure it's also used.
85   // In theory, this variable should be used by the curl library; however, something
86   // is overriding it.
87   char* proxy = std::getenv("http_proxy");
88   if(proxy != nullptr)
89   {
90     curl_easy_setopt(curlHandle, CURLOPT_PROXY, proxy);
91   }
92 }
93
94 // Without a write function or a buffer (file descriptor) to write to, curl will pump out
95 // header/body contents to stdout
96 size_t DummyWrite(char* ptr, size_t size, size_t nmemb, void* userdata)
97 {
98   return size * nmemb;
99 }
100
101 struct ChunkData
102 {
103   std::vector<uint8_t> data;
104 };
105
106 size_t ChunkLoader(char* ptr, size_t size, size_t nmemb, void* userdata)
107 {
108   std::vector<ChunkData>* chunks   = static_cast<std::vector<ChunkData>*>(userdata);
109   int                     numBytes = size * nmemb;
110   chunks->push_back(ChunkData());
111   ChunkData& chunkData = (*chunks)[chunks->size() - 1];
112   chunkData.data.reserve(numBytes);
113   memcpy(&chunkData.data[0], ptr, numBytes);
114   return numBytes;
115 }
116
117 CURLcode DownloadFileDataWithSize(CURL* curlHandle, Dali::Vector<uint8_t>& dataBuffer, size_t dataSize)
118 {
119   CURLcode result(CURLE_OK);
120
121   // create
122   Dali::Internal::Platform::FileWriter fileWriter(dataBuffer, dataSize);
123   FILE*                                dataBufferFilePointer = fileWriter.GetFile();
124   setbuf(dataBufferFilePointer, NULL); // Turn buffering off
125
126   if(NULL != dataBufferFilePointer)
127   {
128     // we only want the body which contains the file data
129     curl_easy_setopt(curlHandle, CURLOPT_HEADER, EXCLUDE_HEADER);
130     curl_easy_setopt(curlHandle, CURLOPT_NOBODY, INCLUDE_BODY);
131
132     // disable the write callback, and get curl to write directly into our data buffer
133     curl_easy_setopt(curlHandle, CURLOPT_WRITEFUNCTION, NULL);
134     curl_easy_setopt(curlHandle, CURLOPT_WRITEDATA, dataBufferFilePointer);
135
136     // synchronous request of the body data
137     result = curl_easy_perform(curlHandle);
138   }
139   return result;
140 }
141
142 CURLcode DownloadFileDataByChunk(CURL* curlHandle, Dali::Vector<uint8_t>& dataBuffer, size_t& dataSize)
143 {
144   // create
145   std::vector<ChunkData> chunks;
146
147   // we only want the body which contains the file data
148   curl_easy_setopt(curlHandle, CURLOPT_HEADER, EXCLUDE_HEADER);
149   curl_easy_setopt(curlHandle, CURLOPT_NOBODY, INCLUDE_BODY);
150
151   // Enable the write callback.
152   curl_easy_setopt(curlHandle, CURLOPT_WRITEFUNCTION, ChunkLoader);
153   curl_easy_setopt(curlHandle, CURLOPT_WRITEDATA, &chunks);
154
155   // synchronous request of the body data
156   CURLcode result = curl_easy_perform(curlHandle);
157
158   // chunks should now contain all of the chunked data. Reassemble into a single vector
159   dataSize = 0;
160   for(size_t i = 0; i < chunks.size(); ++i)
161   {
162     dataSize += chunks[i].data.capacity();
163   }
164   dataBuffer.ResizeUninitialized(dataSize);
165
166   if(DALI_LIKELY(dataSize > 0))
167   {
168     std::uint8_t* dataBufferPtr = dataBuffer.Begin();
169     for(size_t i = 0; i < chunks.size(); ++i)
170     {
171       memcpy(dataBufferPtr, &chunks[i].data[0], chunks[i].data.capacity());
172       dataBufferPtr += chunks[i].data.capacity();
173     }
174   }
175
176   return result;
177 }
178
179 bool DownloadFile(CURL*                  curlHandle,
180                   const std::string&     url,
181                   Dali::Vector<uint8_t>& dataBuffer,
182                   size_t&                dataSize,
183                   size_t                 maximumAllowedSizeBytes,
184                   char*                  errorBuffer)
185 {
186   CURLcode result(CURLE_OK);
187
188   // setup curl to download just the header so we can extract the content length
189   ConfigureCurlOptions(curlHandle, url);
190   curl_easy_setopt(curlHandle, CURLOPT_WRITEFUNCTION, DummyWrite);
191   if(errorBuffer != nullptr)
192   {
193     errorBuffer[0] = 0;
194   }
195
196   // perform the request to get the header
197   result = curl_easy_perform(curlHandle);
198
199   if(result != CURLE_OK)
200   {
201     if(errorBuffer != nullptr)
202     {
203       DALI_LOG_ERROR("Failed to download http header for \"%s\" with error code %d (%s)\n", url.c_str(), result, &errorBuffer[0]);
204     }
205     else
206     {
207       DALI_LOG_ERROR("Failed to download http header for \"%s\" with error code %d\n", url.c_str(), result);
208     }
209     return false;
210   }
211
212   // get the content length, -1 == size is not known
213   curl_off_t size{0};
214   curl_easy_getinfo(curlHandle, CURLINFO_CONTENT_LENGTH_DOWNLOAD_T, &size);
215
216   if(size == -1)
217   {
218     result = DownloadFileDataByChunk(curlHandle, dataBuffer, dataSize);
219   }
220   else if(size >= static_cast<curl_off_t>(maximumAllowedSizeBytes))
221   {
222     DALI_LOG_ERROR("File content length %" CURL_FORMAT_CURL_OFF_T " > max allowed %zu \"%s\" \n", size, maximumAllowedSizeBytes, url.c_str());
223     return false;
224   }
225   else
226   {
227     // If we know the size up front, allocate once and avoid chunk copies.
228     dataSize = static_cast<size_t>(size);
229     result   = DownloadFileDataWithSize(curlHandle, dataBuffer, dataSize);
230     if(result != CURLE_OK)
231     {
232       LogCurlResult(result, errorBuffer, url, "Failed to download file, trying to load by chunk");
233       // In the case where the size is wrong (e.g. on a proxy server that rewrites data),
234       // the data buffer will be corrupt. In this case, try again using the chunk writer.
235       result = DownloadFileDataByChunk(curlHandle, dataBuffer, dataSize);
236     }
237   }
238
239   LogCurlResult(result, errorBuffer, url, "Failed to download image file");
240
241   if(result != CURLE_OK)
242   {
243     return false;
244   }
245   return true;
246 }
247
248 } // unnamed namespace
249
250 namespace Network
251 {
252 CurlEnvironment::CurlEnvironment()
253 {
254   // Must be called before we attempt any loads. e.g. by using curl_easy_init()
255   // and before we start any threads.
256   curl_global_init(CURL_GLOBAL_ALL);
257 }
258
259 CurlEnvironment::~CurlEnvironment()
260 {
261   curl_global_cleanup();
262 }
263
264 bool DownloadRemoteFileIntoMemory(const std::string&     url,
265                                   Dali::Vector<uint8_t>& dataBuffer,
266                                   size_t&                dataSize,
267                                   size_t                 maximumAllowedSizeBytes)
268 {
269   bool result = false;
270
271   if(url.empty())
272   {
273     DALI_LOG_WARNING("empty url requested \n");
274     return false;
275   }
276
277   // start a libcurl easy session, this internally calls curl_global_init, if we ever have more than one download
278   // thread we need to explicity call curl_global_init() on startup from a single thread.
279
280   CURL* curlHandle = curl_easy_init();
281   if(curlHandle)
282   {
283     std::vector<char> errorBuffer(CURL_ERROR_SIZE);
284     curl_easy_setopt(curlHandle, CURLOPT_ERRORBUFFER, &errorBuffer[0]);
285     result = DownloadFile(curlHandle, url, dataBuffer, dataSize, maximumAllowedSizeBytes, &errorBuffer[0]);
286
287     // clean up session
288     curl_easy_cleanup(curlHandle);
289   }
290   return result;
291 }
292
293 } // namespace Network
294
295 } // namespace TizenPlatform
296
297 } // namespace Dali