2 * Copyright (c) 2018 Samsung Electronics Co., Ltd.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 #include <dali/internal/imaging/common/file-download.h>
22 #include <dali/integration-api/debug.h>
24 #include <openssl/crypto.h>
26 #include <curl/curl.h>
27 #include <../ExInclude/InternalFileOperation.h>
30 #include <dali/internal/system/common/file-writer.h>
32 #ifdef TPK_CURL_ENABLED
33 #include <tpkp_curl.h>
34 #endif // TPK_CURL_ENABLED
36 using namespace Dali::Integration;
41 namespace TizenPlatform
44 namespace // unnamed namespace
47 const int CONNECTION_TIMEOUT_SECONDS( 30L );
48 const long VERBOSE_MODE = 0L; // 0 == off, 1 == on
49 const long CLOSE_CONNECTION_ON_ERROR = 1L; // 0 == off, 1 == on
50 const long EXCLUDE_HEADER = 0L;
51 const long INCLUDE_HEADER = 1L;
52 const long INCLUDE_BODY = 0L;
53 const long EXCLUDE_BODY = 1L;
56 * Curl library environment. Direct initialize ensures it's constructed before adaptor
57 * or application creates any threads.
59 static Dali::TizenPlatform::Network::CurlEnvironment gCurlEnvironment;
61 // Without a write function or a buffer (file descriptor) to write to, curl will pump out
62 // header/body contents to stdout
63 size_t __cdecl DummyWrite(char *ptr, size_t size, size_t nmemb, void *userdata)
70 std::vector< uint8_t > data;
73 size_t __cdecl ChunkLoader(char *ptr, size_t size, size_t nmemb, void *userdata)
75 std::vector<ChunkData>* chunks = static_cast<std::vector<ChunkData>*>( userdata );
76 int numBytes = size*nmemb;
77 if( chunks != nullptr )
79 chunks->push_back( ChunkData() );
80 ChunkData& chunkData = (*chunks)[chunks->size()-1];
81 chunkData.data.reserve( numBytes );
82 memcpy( chunkData.data.data(), ptr, numBytes );
87 static size_t __cdecl WriteFunction( void *input, size_t uSize, size_t uCount, void *avg )
89 fwrite( input, uSize, uCount, (FILE*)avg );
90 return uSize * uCount;
93 void InitWriteFunction( void* curlHandle )
95 curl_easy_setopt( curlHandle, CURLOPT_WRITEFUNCTION, WriteFunction );
98 CURLcode DownloadFileDataWithSize( CURL* curlHandle, Dali::Vector<uint8_t>& dataBuffer, size_t dataSize )
100 CURLcode result( CURLE_OK );
103 Dali::Internal::Platform::FileWriter fileWriter( dataBuffer, dataSize );
104 FILE* dataBufferFilePointer = fileWriter.GetFile();
105 if( nullptr != dataBufferFilePointer )
107 // we only want the body which contains the file data
108 curl_easy_setopt( curlHandle, CURLOPT_HEADER, EXCLUDE_HEADER );
109 curl_easy_setopt( curlHandle, CURLOPT_NOBODY, INCLUDE_BODY );
111 // disable the write callback, and get curl to write directly into our data buffer
112 InitWriteFunction( curlHandle );
114 curl_easy_setopt( curlHandle, CURLOPT_WRITEDATA, dataBufferFilePointer );
116 // synchronous request of the body data
117 result = curl_easy_perform( curlHandle );
122 CURLcode DownloadFileDataByChunk( CURL* curlHandle, Dali::Vector<uint8_t>& dataBuffer, size_t& dataSize )
125 std::vector< ChunkData > chunks;
127 // we only want the body which contains the file data
128 curl_easy_setopt( curlHandle, CURLOPT_HEADER, EXCLUDE_HEADER );
129 curl_easy_setopt( curlHandle, CURLOPT_NOBODY, INCLUDE_BODY );
131 // Enable the write callback.
132 curl_easy_setopt( curlHandle, CURLOPT_WRITEFUNCTION, ChunkLoader );
133 curl_easy_setopt( curlHandle, CURLOPT_WRITEDATA, &chunks );
135 // synchronous request of the body data
136 CURLcode result = curl_easy_perform( curlHandle );
138 // chunks should now contain all of the chunked data. Reassemble into a single vector
140 for( size_t i=0; i<chunks.size() ; ++i )
142 dataSize += chunks[i].data.capacity();
144 dataBuffer.Resize(dataSize);
147 for( size_t i=0; i<chunks.size() ; ++i )
149 memcpy( &dataBuffer[offset], chunks[i].data.data(), chunks[i].data.capacity() );
150 offset += chunks[i].data.capacity();
156 void ConfigureCurlOptions( void* curlHandle, const std::string& url )
158 curl_easy_setopt( curlHandle, CURLOPT_URL, url.c_str() );
159 //curl_easy_setopt( curlHandle, CURLOPT_VERBOSE, VERBOSE_MODE );
160 curl_easy_setopt( curlHandle, CURLOPT_PROXY, "109.123.100.31:3128" );
162 // CURLOPT_FAILONERROR is not fail-safe especially when authentication is involved ( see manual )
163 // Removed CURLOPT_FAILONERROR option
164 curl_easy_setopt( curlHandle, CURLOPT_CONNECTTIMEOUT, CONNECTION_TIMEOUT_SECONDS );
165 curl_easy_setopt( curlHandle, CURLOPT_HEADER, INCLUDE_HEADER );
166 curl_easy_setopt( curlHandle, CURLOPT_NOBODY, EXCLUDE_BODY );
169 bool DownloadFile( CURL* curlHandle,
170 const std::string& url,
171 Dali::Vector<uint8_t>& dataBuffer,
173 size_t maximumAllowedSizeBytes )
175 CURLcode result( CURLE_OK );
178 // setup curl to download just the header so we can extract the content length
179 ConfigureCurlOptions( curlHandle, url );
181 curl_easy_setopt( curlHandle, CURLOPT_WRITEFUNCTION, DummyWrite);
183 // perform the request to get the header
184 result = curl_easy_perform( curlHandle );
186 if( result != CURLE_OK)
188 DALI_LOG_ERROR( "Failed to download http header for \"%s\" with error code %d\n", url.c_str(), result );
192 // get the content length, -1 == size is not known
193 curl_easy_getinfo( curlHandle,CURLINFO_CONTENT_LENGTH_DOWNLOAD , &size );
196 if( size >= maximumAllowedSizeBytes )
198 DALI_LOG_ERROR( "File content length %f > max allowed %zu \"%s\" \n", size, maximumAllowedSizeBytes, url.c_str() );
203 // If we know the size up front, allocate once and avoid chunk copies.
204 dataSize = static_cast<size_t>( size );
205 result = DownloadFileDataWithSize( curlHandle, dataBuffer, dataSize );
209 result = DownloadFileDataByChunk( curlHandle, dataBuffer, dataSize );
212 if( result != CURLE_OK )
214 DALI_LOG_ERROR( "Failed to download image file \"%s\" with error code %d\n", url.c_str(), result );
221 } // unnamed namespace
227 std::mutex* CurlEnvironment::mMutexs = NULL;
229 CurlEnvironment::CurlEnvironment()
231 // Must be called before we attempt any loads. e.g. by using curl_easy_init()
232 // and before we start any threads.
233 curl_global_init(CURL_GLOBAL_ALL);
235 // libcurl with openssl needs locking_function and thread id for threadsafe
236 // https://curl.haxx.se/libcurl/c/threadsafe.html
237 // https://www.openssl.org/docs/man1.0.2/crypto/threads.html#DESCRIPTION
238 // SetLockingFunction sets locking_function and get thread id by the guide.
239 SetLockingFunction();
242 CurlEnvironment::~CurlEnvironment()
244 UnsetLockingFunction();
246 curl_global_cleanup();
249 // libcurl with openssl needs locking_function and thread id for threadsafe
250 // https://curl.haxx.se/libcurl/c/threadsafe.html
251 // https://www.openssl.org/docs/man1.0.2/crypto/threads.html#DESCRIPTION
252 void CurlEnvironment::OnOpenSSLLocking( int mode, int n, const char* file, int line )
254 if( mode & CRYPTO_LOCK )
264 void CurlEnvironment::SetLockingFunction()
266 if( mMutexs != NULL )
271 mMutexs = new std::mutex[ CRYPTO_num_locks() ];
273 CRYPTO_set_id_callback( &CurlEnvironment::GetThreadId );
274 CRYPTO_set_locking_callback( &CurlEnvironment::OnOpenSSLLocking );
277 void CurlEnvironment::UnsetLockingFunction()
279 if( mMutexs == NULL )
284 CRYPTO_set_id_callback( NULL );
285 CRYPTO_set_locking_callback( NULL );
291 bool DownloadRemoteFileIntoMemory( const std::string& url,
292 Dali::Vector<uint8_t>& dataBuffer,
294 size_t maximumAllowedSizeBytes )
298 DALI_LOG_WARNING("empty url requested \n");
302 // start a libcurl easy session, this internally calls curl_global_init, if we ever have more than one download
303 // thread we need to explicity call curl_global_init() on startup from a single thread.
305 CURL* curlHandle = curl_easy_init();
307 bool result = DownloadFile( curlHandle, url, dataBuffer, dataSize, maximumAllowedSizeBytes);
310 curl_easy_cleanup( curlHandle );
312 #ifdef TPK_CURL_ENABLED
313 // Clean up tpkp(the module for certificate pinning) resources on Tizen
315 #endif // TPK_CURL_ENABLED
320 } // namespace Network
322 } // namespace TizenPlatform