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