Merge "drag-and-drop: add const prefix to member data of DragData" into devel/master
[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 const int  CONNECTION_TIMEOUT_SECONDS(30L);
40 const int  TIMEOUT_SECONDS(120L);
41 const long VERBOSE_MODE              = 0L; // 0 == off, 1 == on
42 const long CLOSE_CONNECTION_ON_ERROR = 1L; // 0 == off, 1 == on
43 const long EXCLUDE_HEADER            = 0L;
44 const long INCLUDE_HEADER            = 1L;
45 const long INCLUDE_BODY              = 0L;
46 const long EXCLUDE_BODY              = 1L;
47
48 /**
49  * Curl library environment. Direct initialize ensures it's constructed before adaptor
50  * or application creates any threads.
51  */
52 static Dali::TizenPlatform::Network::CurlEnvironment gCurlEnvironment;
53
54 void ConfigureCurlOptions(CURL* curlHandle, const std::string& url)
55 {
56   curl_easy_setopt(curlHandle, CURLOPT_URL, url.c_str());
57   curl_easy_setopt(curlHandle, CURLOPT_VERBOSE, VERBOSE_MODE);
58
59   // CURLOPT_FAILONERROR is not fail-safe especially when authentication is involved ( see manual )
60   // Removed CURLOPT_FAILONERROR option
61   curl_easy_setopt(curlHandle, CURLOPT_CONNECTTIMEOUT, CONNECTION_TIMEOUT_SECONDS);
62   curl_easy_setopt(curlHandle, CURLOPT_TIMEOUT, TIMEOUT_SECONDS);
63   curl_easy_setopt(curlHandle, CURLOPT_HEADER, INCLUDE_HEADER);
64   curl_easy_setopt(curlHandle, CURLOPT_NOBODY, EXCLUDE_BODY);
65   curl_easy_setopt(curlHandle, CURLOPT_FOLLOWLOCATION, 1L);
66   curl_easy_setopt(curlHandle, CURLOPT_MAXREDIRS, 5L);
67
68   // If the proxy variable is set, ensure it's also used.
69   // In theory, this variable should be used by the curl library; however, something
70   // is overriding it.
71   char* proxy = std::getenv("http_proxy");
72   if(proxy != nullptr)
73   {
74     curl_easy_setopt(curlHandle, CURLOPT_PROXY, proxy);
75   }
76 }
77
78 // Without a write function or a buffer (file descriptor) to write to, curl will pump out
79 // header/body contents to stdout
80 size_t DummyWrite(char* ptr, size_t size, size_t nmemb, void* userdata)
81 {
82   return size * nmemb;
83 }
84
85 struct ChunkData
86 {
87   std::vector<uint8_t> data;
88 };
89
90 size_t ChunkLoader(char* ptr, size_t size, size_t nmemb, void* userdata)
91 {
92   std::vector<ChunkData>* chunks   = static_cast<std::vector<ChunkData>*>(userdata);
93   int                     numBytes = size * nmemb;
94   chunks->push_back(ChunkData());
95   ChunkData& chunkData = (*chunks)[chunks->size() - 1];
96   chunkData.data.reserve(numBytes);
97   memcpy(&chunkData.data[0], ptr, numBytes);
98   return numBytes;
99 }
100
101 CURLcode DownloadFileDataWithSize(CURL* curlHandle, Dali::Vector<uint8_t>& dataBuffer, size_t dataSize)
102 {
103   CURLcode result(CURLE_OK);
104
105   // create
106   Dali::Internal::Platform::FileWriter fileWriter(dataBuffer, dataSize);
107   FILE*                                dataBufferFilePointer = fileWriter.GetFile();
108   if(NULL != dataBufferFilePointer)
109   {
110     // we only want the body which contains the file data
111     curl_easy_setopt(curlHandle, CURLOPT_HEADER, EXCLUDE_HEADER);
112     curl_easy_setopt(curlHandle, CURLOPT_NOBODY, INCLUDE_BODY);
113
114     // disable the write callback, and get curl to write directly into our data buffer
115     curl_easy_setopt(curlHandle, CURLOPT_WRITEFUNCTION, NULL);
116     curl_easy_setopt(curlHandle, CURLOPT_WRITEDATA, dataBufferFilePointer);
117
118     // synchronous request of the body data
119     result = curl_easy_perform(curlHandle);
120   }
121   return result;
122 }
123
124 CURLcode DownloadFileDataByChunk(CURL* curlHandle, Dali::Vector<uint8_t>& dataBuffer, size_t& dataSize)
125 {
126   // create
127   std::vector<ChunkData> chunks;
128
129   // we only want the body which contains the file data
130   curl_easy_setopt(curlHandle, CURLOPT_HEADER, EXCLUDE_HEADER);
131   curl_easy_setopt(curlHandle, CURLOPT_NOBODY, INCLUDE_BODY);
132
133   // Enable the write callback.
134   curl_easy_setopt(curlHandle, CURLOPT_WRITEFUNCTION, ChunkLoader);
135   curl_easy_setopt(curlHandle, CURLOPT_WRITEDATA, &chunks);
136
137   // synchronous request of the body data
138   CURLcode result = curl_easy_perform(curlHandle);
139
140   // chunks should now contain all of the chunked data. Reassemble into a single vector
141   dataSize = 0;
142   for(size_t i = 0; i < chunks.size(); ++i)
143   {
144     dataSize += chunks[i].data.capacity();
145   }
146   dataBuffer.ResizeUninitialized(dataSize);
147
148   if(DALI_LIKELY(dataSize > 0))
149   {
150     std::uint8_t* dataBufferPtr = dataBuffer.Begin();
151     for(size_t i = 0; i < chunks.size(); ++i)
152     {
153       memcpy(dataBufferPtr, &chunks[i].data[0], chunks[i].data.capacity());
154       dataBufferPtr += chunks[i].data.capacity();
155     }
156   }
157
158   return result;
159 }
160
161 bool DownloadFile(CURL*                  curlHandle,
162                   const std::string&     url,
163                   Dali::Vector<uint8_t>& dataBuffer,
164                   size_t&                dataSize,
165                   size_t                 maximumAllowedSizeBytes,
166                   char*                  errorBuffer)
167 {
168   CURLcode result(CURLE_OK);
169   double   size(0);
170
171   // setup curl to download just the header so we can extract the content length
172   ConfigureCurlOptions(curlHandle, url);
173   curl_easy_setopt(curlHandle, CURLOPT_WRITEFUNCTION, DummyWrite);
174   if(errorBuffer != nullptr)
175   {
176     errorBuffer[0] = 0;
177   }
178
179   // perform the request to get the header
180   result = curl_easy_perform(curlHandle);
181
182   if(result != CURLE_OK)
183   {
184     if(errorBuffer != nullptr)
185     {
186       DALI_LOG_ERROR("Failed to download http header for \"%s\" with error code %d (%s)\n", url.c_str(), result, &errorBuffer[0]);
187     }
188     else
189     {
190       DALI_LOG_ERROR("Failed to download http header for \"%s\" with error code %d\n", url.c_str(), result);
191     }
192     return false;
193   }
194
195   // get the content length, -1 == size is not known
196   curl_easy_getinfo(curlHandle, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &size);
197
198   if(size >= maximumAllowedSizeBytes)
199   {
200     DALI_LOG_ERROR("File content length %f > max allowed %zu \"%s\" \n", size, maximumAllowedSizeBytes, url.c_str());
201     return false;
202   }
203   else if(size > 0)
204   {
205     // If we know the size up front, allocate once and avoid chunk copies.
206     dataSize = static_cast<size_t>(size);
207     result   = DownloadFileDataWithSize(curlHandle, dataBuffer, dataSize);
208   }
209   else
210   {
211     result = DownloadFileDataByChunk(curlHandle, dataBuffer, dataSize);
212   }
213
214   if(result != CURLE_OK)
215   {
216     if(errorBuffer != nullptr)
217     {
218       DALI_LOG_ERROR("Failed to download image file \"%s\" with error code %d\n", url.c_str(), result);
219     }
220     else
221     {
222       DALI_LOG_ERROR("Failed to download image file \"%s\" with error code %d (%s)\n", url.c_str(), result, errorBuffer);
223     }
224     return false;
225   }
226   return true;
227 }
228
229 } // unnamed namespace
230
231 namespace Network
232 {
233 CurlEnvironment::CurlEnvironment()
234 {
235   // Must be called before we attempt any loads. e.g. by using curl_easy_init()
236   // and before we start any threads.
237   curl_global_init(CURL_GLOBAL_ALL);
238 }
239
240 CurlEnvironment::~CurlEnvironment()
241 {
242   curl_global_cleanup();
243 }
244
245 bool DownloadRemoteFileIntoMemory(const std::string&     url,
246                                   Dali::Vector<uint8_t>& dataBuffer,
247                                   size_t&                dataSize,
248                                   size_t                 maximumAllowedSizeBytes)
249 {
250   bool result = false;
251
252   if(url.empty())
253   {
254     DALI_LOG_WARNING("empty url requested \n");
255     return false;
256   }
257
258   // start a libcurl easy session, this internally calls curl_global_init, if we ever have more than one download
259   // thread we need to explicity call curl_global_init() on startup from a single thread.
260
261   CURL* curlHandle = curl_easy_init();
262   if(curlHandle)
263   {
264     std::vector<char> errorBuffer(CURL_ERROR_SIZE);
265     curl_easy_setopt(curlHandle, CURLOPT_ERRORBUFFER, &errorBuffer[0]);
266     result = DownloadFile(curlHandle, url, dataBuffer, dataSize, maximumAllowedSizeBytes, &errorBuffer[0]);
267
268     // clean up session
269     curl_easy_cleanup(curlHandle);
270   }
271   return result;
272 }
273
274 } // namespace Network
275
276 } // namespace TizenPlatform
277
278 } // namespace Dali