1 /**************************************************************
2  *
3  * Licensed to the Apache Software Foundation (ASF) under one
4  * or more contributor license agreements.  See the NOTICE file
5  * distributed with this work for additional information
6  * regarding copyright ownership.  The ASF licenses this file
7  * to you under the Apache License, Version 2.0 (the
8  * "License"); you may not use this file except in compliance
9  * with the License.  You may obtain a copy of the License at
10  *
11  *   http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing,
14  * software distributed under the License is distributed on an
15  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16  * KIND, either express or implied.  See the License for the
17  * specific language governing permissions and limitations
18  * under the License.
19  *
20  *************************************************************/
21 
22 
23 
24 // MARKER(update_precomp.py): autogen include statement, do not remove
25 #include "precompiled_extensions.hxx"
26 
27 #if defined WNT
28 #ifdef _MSC_VER
29 #pragma warning(push, 1) /* disable warnings within system headers */
30 #endif
31 #include <curl/curl.h>
32 #ifdef _MSC_VER
33 #pragma warning(pop)
34 #endif
35 #else
36 #include <curl/curl.h>
37 #endif
38 #include <com/sun/star/beans/PropertyValue.hpp>
39 #include <com/sun/star/container/XNameAccess.hpp>
40 #include <com/sun/star/lang/XMultiServiceFactory.hpp>
41 
42 #include "download.hxx"
43 
44 namespace beans = com::sun::star::beans ;
45 namespace container = com::sun::star::container ;
46 namespace lang = com::sun::star::lang ;
47 namespace uno = com::sun::star::uno ;
48 
49 #define UNISTRING(s) rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(s))
50 
51 
52 struct OutData
53 {
54     rtl::Reference< DownloadInteractionHandler >Handler;
55     rtl::OUString   File;
56     rtl::OUString   DestinationDir;
57     oslFileHandle   FileHandle;
58     sal_uInt64      Offset;
59     osl::Condition& StopCondition;
60     CURL *curl;
61 
OutDataOutData62     OutData(osl::Condition& rCondition) : FileHandle(NULL), Offset(0), StopCondition(rCondition), curl(NULL) {};
63 };
64 
65 //------------------------------------------------------------------------------
66 
openFile(OutData & out)67 static void openFile( OutData& out )
68 {
69     char * effective_url;
70     curl_easy_getinfo(out.curl, CURLINFO_EFFECTIVE_URL, &effective_url);
71 
72     double fDownloadSize;
73     curl_easy_getinfo(out.curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &fDownloadSize);
74 
75     rtl::OString aURL(effective_url);
76 
77     // ensure no trailing '/'
78     sal_Int32 nLen = aURL.getLength();
79     while( (nLen > 0) && ('/' == aURL[nLen-1]) )
80         aURL = aURL.copy(0, --nLen);
81 
82     // extract file name last '/'
83     sal_Int32 nIndex = aURL.lastIndexOf('/');
84     if( nIndex > 0 )
85     {
86         out.File = out.DestinationDir + rtl::OStringToOUString(aURL.copy(nIndex), RTL_TEXTENCODING_UTF8);
87 
88         oslFileError rc;
89 
90         // Give the user an overwrite warning if the target file exists
91         const sal_Int32 openFlags = osl_File_OpenFlag_Write | osl_File_OpenFlag_Create;
92         do
93         {
94             rc = osl_openFile(out.File.pData, &out.FileHandle, openFlags);
95 
96             if( osl_File_E_EXIST == rc && ! out.Handler->downloadTargetExists(out.File) )
97             {
98                 out.StopCondition.set();
99                 break;
100             }
101 
102         } while( osl_File_E_EXIST == rc );
103 
104         if( osl_File_E_None == rc )
105             out.Handler->downloadStarted(out.File, (sal_Int64) fDownloadSize);
106     }
107 }
108 
109 //------------------------------------------------------------------------------
110 
111 static inline rtl::OString
getStringValue(const uno::Reference<container::XNameAccess> & xNameAccess,const rtl::OUString & aName)112 getStringValue(const uno::Reference< container::XNameAccess >& xNameAccess, const rtl::OUString& aName)
113 {
114     rtl::OString aRet;
115 
116     OSL_ASSERT(xNameAccess->hasByName(aName));
117     uno::Any aValue = xNameAccess->getByName(aName);
118 
119     return rtl::OUStringToOString(aValue.get<rtl::OUString>(), RTL_TEXTENCODING_UTF8);
120 }
121 
122 //------------------------------------------------------------------------------
123 
124 static inline sal_Int32
getInt32Value(const uno::Reference<container::XNameAccess> & xNameAccess,const rtl::OUString & aName,sal_Int32 nDefault=-1)125 getInt32Value(const uno::Reference< container::XNameAccess >& xNameAccess,
126                     const rtl::OUString& aName, sal_Int32 nDefault=-1)
127 {
128     OSL_ASSERT(xNameAccess->hasByName(aName));
129     uno::Any aValue = xNameAccess->getByName(aName);
130 
131     sal_Int32 n=nDefault;
132     aValue >>= n;
133     return n;
134 }
135 
136 //------------------------------------------------------------------------------
137 
138 static size_t
write_function(void * ptr,size_t size,size_t nmemb,void * stream)139 write_function( void *ptr, size_t size, size_t nmemb, void *stream )
140 {
141     OutData *out = reinterpret_cast < OutData * > (stream);
142 
143     if( NULL == out->FileHandle )
144         openFile(*out);
145 
146     sal_uInt64 nBytesWritten = 0;
147 
148     if( NULL != out->FileHandle )
149         osl_writeFile(out->FileHandle, ptr, size * nmemb, &nBytesWritten);
150 
151     return (size_t) nBytesWritten;
152 }
153 
154 //------------------------------------------------------------------------------
155 
156 static int
progress_callback(void * clientp,double dltotal,double dlnow,double ultotal,double ulnow)157 progress_callback( void *clientp, double dltotal, double dlnow, double ultotal, double ulnow )
158 {
159     (void) ultotal;
160     (void) ulnow;
161 
162     OutData *out = reinterpret_cast < OutData * > (clientp);
163 
164     OSL_ASSERT( out );
165 
166     if( ! out->StopCondition.check() )
167     {
168         double fPercent = 0;
169         if ( dltotal + out->Offset )
170             fPercent = (dlnow + out->Offset) * 100 / (dltotal + out->Offset);
171         if( fPercent < 0 )
172             fPercent = 0;
173 
174         // Do not report progress for redirection replies
175         long nCode;
176         curl_easy_getinfo(out->curl, CURLINFO_RESPONSE_CODE, &nCode);
177         if( (nCode != 302) && (nCode != 303) && (dltotal > 0) )
178             out->Handler->downloadProgressAt((sal_Int8)fPercent);
179 
180         return 0;
181     }
182 
183     // If stop condition is set, return non 0 value to abort
184     return -1;
185 }
186 
187 //------------------------------------------------------------------------------
188 
189 void
getProxyForURL(const rtl::OUString & rURL,rtl::OString & rHost,sal_Int32 & rPort) const190 Download::getProxyForURL(const rtl::OUString& rURL, rtl::OString& rHost, sal_Int32& rPort) const
191 {
192     if( !m_xContext.is() )
193         throw uno::RuntimeException(
194             UNISTRING( "Download: empty component context" ),
195             uno::Reference< uno::XInterface >() );
196 
197     uno::Reference< lang::XMultiComponentFactory > xServiceManager(m_xContext->getServiceManager());
198 
199     if( !xServiceManager.is() )
200         throw uno::RuntimeException(
201             UNISTRING( "Download: unable to obtain service manager from component context" ),
202             uno::Reference< uno::XInterface >() );
203 
204     uno::Reference< lang::XMultiServiceFactory > xConfigProvider(
205         xServiceManager->createInstanceWithContext( UNISTRING( "com.sun.star.configuration.ConfigurationProvider" ), m_xContext ),
206         uno::UNO_QUERY_THROW);
207 
208     beans::PropertyValue aProperty;
209     aProperty.Name  = UNISTRING( "nodepath" );
210     aProperty.Value = uno::makeAny( UNISTRING("org.openoffice.Inet/Settings") );
211 
212     uno::Sequence< uno::Any > aArgumentList( 1 );
213     aArgumentList[0] = uno::makeAny( aProperty );
214 
215     uno::Reference< container::XNameAccess > xNameAccess(
216         xConfigProvider->createInstanceWithArguments(
217             UNISTRING("com.sun.star.configuration.ConfigurationAccess"), aArgumentList ),
218         uno::UNO_QUERY_THROW );
219 
220     OSL_ASSERT(xNameAccess->hasByName(UNISTRING("ooInetProxyType")));
221     uno::Any aValue = xNameAccess->getByName(UNISTRING("ooInetProxyType"));
222 
223     sal_Int32 nProxyType = aValue.get< sal_Int32 >();
224     if( 0 != nProxyType ) // type 0 means "direct connection to the internet
225     {
226         if( rURL.matchAsciiL(RTL_CONSTASCII_STRINGPARAM("http:")) )
227         {
228             rHost = getStringValue(xNameAccess, UNISTRING("ooInetHTTPProxyName"));
229             rPort = getInt32Value(xNameAccess, UNISTRING("ooInetHTTPProxyPort"));
230         }
231         else if( rURL.matchAsciiL(RTL_CONSTASCII_STRINGPARAM("https:")) )
232         {
233             rHost = getStringValue(xNameAccess, UNISTRING("ooInetHTTPSProxyName"));
234             rPort = getInt32Value(xNameAccess, UNISTRING("ooInetHTTPSProxyPort"));
235         }
236         else if( rURL.matchAsciiL(RTL_CONSTASCII_STRINGPARAM("ftp:")) )
237         {
238             rHost = getStringValue(xNameAccess, UNISTRING("ooInetFTPProxyName"));
239             rPort = getInt32Value(xNameAccess, UNISTRING("ooInetFTPProxyPort"));
240         }
241     }
242 }
243 
244 //------------------------------------------------------------------------------
245 
curl_run(const rtl::OUString & rURL,OutData & out,const rtl::OString & aProxyHost,sal_Int32 nProxyPort)246 bool curl_run(const rtl::OUString& rURL, OutData& out, const rtl::OString& aProxyHost, sal_Int32 nProxyPort)
247 {
248     /* Need to investigate further whether it is necessary to call
249      * curl_global_init or not - leave it for now (as the ftp UCB content
250      * provider does as well).
251      */
252 
253     CURL * pCURL = curl_easy_init();
254     bool ret = false;
255 
256     if( NULL != pCURL )
257     {
258         out.curl = pCURL;
259 
260         rtl::OString aURL(rtl::OUStringToOString(rURL, RTL_TEXTENCODING_UTF8));
261         curl_easy_setopt(pCURL, CURLOPT_URL, aURL.getStr());
262 
263         // abort on http errors
264         curl_easy_setopt(pCURL, CURLOPT_FAILONERROR, 1);
265 
266         // enable redirection
267         curl_easy_setopt(pCURL, CURLOPT_FOLLOWLOCATION, 1);
268 
269         // write function
270         curl_easy_setopt(pCURL, CURLOPT_WRITEDATA, &out);
271         curl_easy_setopt(pCURL, CURLOPT_WRITEFUNCTION, &write_function);
272 
273         // progress handler - Condition::check unfortunatly is not defined const
274         curl_easy_setopt(pCURL, CURLOPT_NOPROGRESS, 0);
275         curl_easy_setopt(pCURL, CURLOPT_PROGRESSFUNCTION, &progress_callback);
276         curl_easy_setopt(pCURL, CURLOPT_PROGRESSDATA, &out);
277 
278         // proxy
279         curl_easy_setopt(pCURL, CURLOPT_PROXY, aProxyHost.getStr());
280         curl_easy_setopt(pCURL, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
281         if( -1 != nProxyPort )
282             curl_easy_setopt(pCURL, CURLOPT_PROXYPORT, nProxyPort);
283 
284         if( out.Offset > 0 )
285         {
286             // curl_off_t offset = nOffset; libcurl seems to be compiled with large
287             // file support (and we not) ..
288             sal_Int64 offset = (sal_Int64) out.Offset;
289             curl_easy_setopt(pCURL, CURLOPT_RESUME_FROM_LARGE, offset);
290         }
291 
292         CURLcode cc = curl_easy_perform(pCURL);
293 
294         // treat zero byte downloads as errors
295         if( NULL == out.FileHandle )
296             openFile(out);
297 
298         if( CURLE_OK == cc )
299         {
300             out.Handler->downloadFinished(out.File);
301             ret = true;
302         }
303 
304         if ( CURLE_PARTIAL_FILE  == cc )
305         {
306             // this sometimes happens, when a user throws away his user data, but has already
307             // completed the download of an update.
308             double fDownloadSize;
309             curl_easy_getinfo( pCURL, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &fDownloadSize );
310             if ( -1 == fDownloadSize )
311             {
312                 out.Handler->downloadFinished(out.File);
313                 ret = true;
314             }
315         }
316 
317         // Avoid target file being removed
318         else if( (CURLE_ABORTED_BY_CALLBACK == cc) || out.StopCondition.check() )
319             ret = true;
320 
321         // Only report errors when not stopped
322         else
323         {
324             rtl::OString aMessage(RTL_CONSTASCII_STRINGPARAM("Unknown error"));
325 
326             const char * error_message = curl_easy_strerror(cc);
327             if( NULL != error_message )
328                 aMessage = error_message;
329 
330             if ( CURLE_HTTP_RETURNED_ERROR == cc )
331             {
332                 long nError;
333                 curl_easy_getinfo( pCURL, CURLINFO_RESPONSE_CODE, &nError );
334 
335                 if ( 403 == nError )
336                     aMessage += rtl::OString( RTL_CONSTASCII_STRINGPARAM( " 403: Access denied!" ) );
337                 else if ( 404 == nError )
338                     aMessage += rtl::OString( RTL_CONSTASCII_STRINGPARAM( " 404: File not found!" ) );
339                 else if ( 416 == nError )
340                 {
341                     // we got this error probably, because we already downloaded the file
342                     out.Handler->downloadFinished(out.File);
343                     ret = true;
344                 }
345                 else
346                 {
347                     aMessage += rtl::OString( RTL_CONSTASCII_STRINGPARAM( ":error code = " ) );
348                     aMessage += aMessage.valueOf( nError );
349                     aMessage += rtl::OString( RTL_CONSTASCII_STRINGPARAM( " !" ) );
350                 }
351             }
352             if ( !ret )
353                 out.Handler->downloadStalled( rtl::OStringToOUString(aMessage, RTL_TEXTENCODING_UTF8) );
354         }
355 
356         curl_easy_cleanup(pCURL);
357     }
358 
359     return ret;
360 }
361 
362 //------------------------------------------------------------------------------
363 
364 bool
start(const rtl::OUString & rURL,const rtl::OUString & rFile,const rtl::OUString & rDestinationDir)365 Download::start(const rtl::OUString& rURL, const rtl::OUString& rFile, const rtl::OUString& rDestinationDir)
366 {
367     OSL_ASSERT( m_aHandler.is() );
368 
369     OutData out(m_aCondition);
370     rtl::OUString aFile( rFile );
371 
372     // when rFile is empty, there is no remembered file name. If there is already a file with the
373     // same name ask the user if she wants to resume a download or restart the download
374     if ( !aFile.getLength() )
375     {
376         // GetFileName()
377         rtl::OUString aURL( rURL );
378         // ensure no trailing '/'
379         sal_Int32 nLen = aURL.getLength();
380         while( (nLen > 0) && ('/' == aURL[ nLen-1 ]) )
381             aURL = aURL.copy( 0, --nLen );
382 
383         // extract file name last '/'
384         sal_Int32 nIndex = aURL.lastIndexOf('/');
385         aFile = rDestinationDir + aURL.copy( nIndex );
386 
387         // check for existing file
388         oslFileError rc = osl_openFile( aFile.pData, &out.FileHandle, osl_File_OpenFlag_Write | osl_File_OpenFlag_Create );
389         osl_closeFile(out.FileHandle);
390         out.FileHandle = NULL;
391 
392         if( osl_File_E_EXIST == rc )
393         {
394             if ( m_aHandler->checkDownloadDestination( aURL.copy( nIndex+1 ) ) )
395             {
396                 osl_removeFile( aFile.pData );
397                 aFile = rtl::OUString();
398             }
399             else
400                 m_aHandler->downloadStarted( aFile, 0 );
401         }
402         else
403         {
404             osl_removeFile( aFile.pData );
405             aFile = rtl::OUString();
406         }
407     }
408 
409     out.File = aFile;
410     out.DestinationDir = rDestinationDir;
411     out.Handler = m_aHandler;
412 
413     if( aFile.getLength() > 0 )
414     {
415         oslFileError rc = osl_openFile(aFile.pData, &out.FileHandle, osl_File_OpenFlag_Write);
416 
417         if( osl_File_E_None == rc )
418         {
419             // Set file pointer to the end of the file on resume
420             if( osl_File_E_None == osl_setFilePos(out.FileHandle, osl_Pos_End, 0) )
421             {
422                 osl_getFilePos(out.FileHandle, &out.Offset);
423             }
424         }
425         else if( osl_File_E_NOENT == rc ) // file has been deleted meanwhile ..
426             out.File = rtl::OUString();
427     }
428 
429     rtl::OString aProxyHost;
430     sal_Int32    nProxyPort = -1;
431     getProxyForURL(rURL, aProxyHost, nProxyPort);
432 
433     bool ret = curl_run(rURL, out, aProxyHost, nProxyPort);
434 
435     if( NULL != out.FileHandle )
436     {
437         osl_syncFile(out.FileHandle);
438         osl_closeFile(out.FileHandle);
439 
440 // #i90930# Don't remove already downloaded bits, when curl_run reports an error
441 // because later calls might be successful
442 //        if( ! ret )
443 //            osl_removeFile(out.File.pData);
444     }
445 
446     m_aCondition.reset();
447     return ret;
448 }
449 
450 //------------------------------------------------------------------------------
451 
452 void
stop()453 Download::stop()
454 {
455     m_aCondition.set();
456 }
457