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_scripting.hxx"
26 #include "scripthandler.hxx"
27 
28 #include <osl/mutex.hxx>
29 
30 #include <com/sun/star/frame/DispatchResultEvent.hpp>
31 #include <com/sun/star/frame/DispatchResultState.hpp>
32 #include <com/sun/star/frame/XController.hpp>
33 #include <com/sun/star/frame/XModel.hpp>
34 
35 #include <com/sun/star/document/XEmbeddedScripts.hpp>
36 #include <com/sun/star/document/XScriptInvocationContext.hpp>
37 
38 #include <com/sun/star/lang/XSingleServiceFactory.hpp>
39 
40 #include <com/sun/star/script/provider/XScriptProviderSupplier.hpp>
41 #include <com/sun/star/script/provider/XScriptProviderFactory.hpp>
42 #include <com/sun/star/script/provider/ScriptFrameworkErrorType.hpp>
43 
44 #include <rtl/uri.hxx>
45 #include <sfx2/objsh.hxx>
46 #include <sfx2/frame.hxx>
47 #include <sfx2/sfxdlg.hxx>
48 #include <vcl/abstdlg.hxx>
49 #include <tools/diagnose_ex.h>
50 
51 #include <cppuhelper/factory.hxx>
52 #include <cppuhelper/exc_hlp.hxx>
53 #include <util/util.hxx>
54 #include <framework/documentundoguard.hxx>
55 
56 #include "com/sun/star/uno/XComponentContext.hpp"
57 #include "com/sun/star/uri/XUriReference.hpp"
58 #include "com/sun/star/uri/XUriReferenceFactory.hpp"
59 #include "com/sun/star/uri/XVndSunStarScriptUrl.hpp"
60 #include "com/sun/star/beans/XPropertySet.hpp"
61 
62 using namespace ::com::sun::star;
63 using namespace ::com::sun::star::uno;
64 using namespace ::com::sun::star::frame;
65 using namespace ::com::sun::star::util;
66 using namespace ::com::sun::star::beans;
67 using namespace ::com::sun::star::lang;
68 using namespace ::com::sun::star::script;
69 using namespace ::com::sun::star::script::provider;
70 using namespace ::com::sun::star::document;
71 
72 namespace scripting_protocolhandler
73 {
74 
75 const sal_Char * const MYSERVICENAME = "com.sun.star.frame.ProtocolHandler";
76 const sal_Char * const MYIMPLNAME = "com.sun.star.comp.ScriptProtocolHandler";
77 const sal_Char * MYSCHEME = "vnd.sun.star.script";
78 const sal_Int32 MYSCHEME_LEN = 20;
79 
80 void SAL_CALL ScriptProtocolHandler::initialize(
81     const css::uno::Sequence < css::uno::Any >& aArguments )
82     throw ( css::uno::Exception )
83 {
84     if ( m_bInitialised )
85     {
86         return ;
87     }
88 
89     // first argument contains a reference to the frame (may be empty or the desktop,
90     // but usually it's a "real" frame)
91     if ( aArguments.getLength() &&
92          sal_False == ( aArguments[ 0 ] >>= m_xFrame ) )
93     {
94         ::rtl::OUString temp = OUSTR( "ScriptProtocolHandler::initialize: could not extract reference to the frame" );
95         throw RuntimeException( temp, Reference< XInterface >() );
96     }
97 
98     ENSURE_OR_THROW( m_xFactory.is(), "ScriptProtocolHandler::initialize: No Service Manager available" );
99     m_bInitialised = true;
100 }
101 
102 Reference< XDispatch > SAL_CALL ScriptProtocolHandler::queryDispatch(
103     const URL& aURL, const ::rtl::OUString& sTargetFrameName, sal_Int32 nSearchFlags )
104     throw( ::com::sun::star::uno::RuntimeException )
105 {
106 	(void)sTargetFrameName;
107 	(void)nSearchFlags;
108 
109     Reference< XDispatch > xDispatcher;
110     // get scheme of url
111 
112     Reference< uri::XUriReferenceFactory > xFac (
113          m_xFactory->createInstance( rtl::OUString::createFromAscii(
114             "com.sun.star.uri.UriReferenceFactory") ) , UNO_QUERY );
115     if ( xFac.is() )
116     {
117         Reference<  uri::XUriReference > uriRef(
118             xFac->parse( aURL.Complete ), UNO_QUERY );
119         if ( uriRef.is() )
120         {
121             if ( uriRef->getScheme().equals( ::rtl::OUString::createFromAscii( ::scripting_protocolhandler::MYSCHEME ) ) )
122             {
123                 xDispatcher = this;
124             }
125         }
126     }
127 
128     return xDispatcher;
129 }
130 
131 Sequence< Reference< XDispatch > > SAL_CALL
132 ScriptProtocolHandler::queryDispatches(
133 const Sequence < DispatchDescriptor >& seqDescriptor )
134 throw( RuntimeException )
135 {
136     sal_Int32 nCount = seqDescriptor.getLength();
137     Sequence< Reference< XDispatch > > lDispatcher( nCount );
138     for ( sal_Int32 i = 0; i < nCount; ++i )
139     {
140         lDispatcher[ i ] = this->queryDispatch( seqDescriptor[ i ].FeatureURL,
141                                                 seqDescriptor[ i ].FrameName,
142                                                 seqDescriptor[ i ].SearchFlags );
143     }
144     return lDispatcher;
145 }
146 
147 void SAL_CALL ScriptProtocolHandler::dispatchWithNotification(
148     const URL& aURL, const Sequence < PropertyValue >& lArgs,
149     const Reference< XDispatchResultListener >& xListener )
150     throw ( RuntimeException )
151 {
152 
153     sal_Bool bSuccess = sal_False;
154     Any invokeResult;
155 	bool bCaughtException = sal_False;
156 	Any aException;
157     Sequence< Any > inArgs( 0 );
158 
159     if ( m_bInitialised )
160     {
161         ::rtl::OUString aReferer;
162         if ( lArgs.getLength() > 0 )
163         {
164             int argCount = 0;
165             for ( int index = 0; index < lArgs.getLength(); index++ )
166             {
167                 // The propertyval named "Referer"
168                 // is not an argument to be passed to script
169                 if ( lArgs[ index ].Name.compareToAscii("Referer") == 0 ) {
170                     lArgs [ index ].Value >>= aReferer;
171                 } else {
172                     inArgs.realloc( ++argCount );
173                     inArgs[ argCount - 1 ] = lArgs[ index ].Value;
174                 }
175             }
176         }
177         try
178         {
179             ::rtl::OUString xStringUri = ::rtl::Uri::decode( aURL.Complete,
180                 rtl_UriDecodeWithCharset, RTL_TEXTENCODING_UTF8 );
181             bool bIsDocumentScript = ( xStringUri.indexOfAsciiL( RTL_CONSTASCII_STRINGPARAM( "document" ) ) !=-1 );
182             bool bRefererIsTrusted = ( aReferer.compareToAscii("private:", 8) == 0 );
183 
184             // obtain the component for our security check. We could check bIsDocumentScript but the "location" could be forged
185             if ( getScriptInvocation() ) {
186                     Reference< XEmbeddedScripts > xDocumentScripts;
187                     xDocumentScripts.set( m_xScriptInvocation->getScriptContainer(), UNO_SET_THROW );
188 
189                 OSL_ENSURE( xDocumentScripts.is(), "ScriptProtocolHandler::dispatchWithNotification: can't do the security check!" );
190                 if ( !xDocumentScripts.is() ||
191                      ( !bRefererIsTrusted && !xDocumentScripts->getAllowMacroExecution() ) )
192                     return;
193             }
194 
195             // Creates a ScriptProvider ( if one is not created allready )
196             createScriptProvider();
197 
198             Reference< provider::XScript > xFunc =
199                 m_xScriptProvider->getScript( aURL.Complete );
200             ENSURE_OR_THROW( xFunc.is(),
201                 "ScriptProtocolHandler::dispatchWithNotification: validate xFunc - unable to obtain XScript interface" );
202 
203 
204             Sequence< Any > outArgs( 0 );
205             Sequence< sal_Int16 > outIndex;
206 
207             // attempt to protect the document against the script tampering with its Undo Context
208             ::std::auto_ptr< ::framework::DocumentUndoGuard > pUndoGuard;
209             if ( bIsDocumentScript )
210                 pUndoGuard.reset( new ::framework::DocumentUndoGuard( m_xScriptInvocation ) );
211 
212             bSuccess = sal_False;
213             while ( !bSuccess )
214             {
215                 Any aFirstCaughtException;
216                 try
217                 {
218                     invokeResult = xFunc->invoke( inArgs, outIndex, outArgs );
219                     bSuccess = sal_True;
220                 }
221                 catch( const provider::ScriptFrameworkErrorException& se )
222                 {
223                     if  ( !aFirstCaughtException.hasValue() )
224                         aFirstCaughtException = ::cppu::getCaughtException();
225 
226                     if ( se.errorType != provider::ScriptFrameworkErrorType::NO_SUCH_SCRIPT )
227                         // the only condition which allows us to retry is if there is no method with the
228                         // given name/signature
229                         ::cppu::throwException( aFirstCaughtException );
230 
231                     if ( inArgs.getLength() == 0 )
232                         // no chance to retry if we can't strip more in-args
233                         ::cppu::throwException( aFirstCaughtException );
234 
235                     // strip one argument, then retry
236                     inArgs.realloc( inArgs.getLength() - 1 );
237                 }
238             }
239         }
240         // Office doesn't handle exceptions rethrown here very well, it cores,
241         // all we can is log them and then set fail for the dispatch event!
242         // (if there is a listener of course)
243         catch ( const Exception & e )
244         {
245             aException = ::cppu::getCaughtException();
246 
247             ::rtl::OUString reason = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "ScriptProtocolHandler::dispatch: caught " ) );
248 
249             invokeResult <<= reason.concat( aException.getValueTypeName() ).concat( e.Message );
250 
251 			bCaughtException = sal_True;
252         }
253     }
254     else
255     {
256         ::rtl::OUString reason = ::rtl::OUString::createFromAscii(
257         "ScriptProtocolHandler::dispatchWithNotification failed, ScriptProtocolHandler not initialised"
258         );
259         invokeResult <<= reason;
260     }
261 
262 	if ( bCaughtException )
263 	{
264 		SfxAbstractDialogFactory* pFact = SfxAbstractDialogFactory::Create();
265 
266 		if ( pFact != NULL )
267 		{
268 			VclAbstractDialog* pDlg =
269 				pFact->CreateScriptErrorDialog( NULL, aException );
270 
271 			if ( pDlg != NULL )
272 			{
273 				pDlg->Execute();
274 				delete pDlg;
275 			}
276 		}
277    	}
278 
279     if ( xListener.is() )
280     {
281         // always call dispatchFinished(), because we didn't load a document but
282         // executed a macro instead!
283         ::com::sun::star::frame::DispatchResultEvent aEvent;
284 
285         aEvent.Source = static_cast< ::cppu::OWeakObject* >( this );
286         aEvent.Result = invokeResult;
287         if ( bSuccess )
288         {
289             aEvent.State = ::com::sun::star::frame::DispatchResultState::SUCCESS;
290         }
291         else
292         {
293             aEvent.State = ::com::sun::star::frame::DispatchResultState::FAILURE;
294         }
295 
296         try
297         {
298             xListener->dispatchFinished( aEvent ) ;
299         }
300         catch(RuntimeException & e)
301         {
302             OSL_TRACE(
303             "ScriptProtocolHandler::dispatchWithNotification: caught RuntimeException"
304             "while dispatchFinished %s",
305             ::rtl::OUStringToOString( e.Message,
306             RTL_TEXTENCODING_ASCII_US ).pData->buffer );
307         }
308     }
309 }
310 
311 void SAL_CALL ScriptProtocolHandler::dispatch(
312 const URL& aURL, const Sequence< PropertyValue >& lArgs )
313 throw ( RuntimeException )
314 {
315     dispatchWithNotification( aURL, lArgs, Reference< XDispatchResultListener >() );
316 }
317 
318 void SAL_CALL ScriptProtocolHandler::addStatusListener(
319 const Reference< XStatusListener >& xControl, const URL& aURL )
320 throw ( RuntimeException )
321 {
322 	(void)xControl;
323 	(void)aURL;
324 
325     // implement if status is supported
326 }
327 
328 void SAL_CALL ScriptProtocolHandler::removeStatusListener(
329 const Reference< XStatusListener >& xControl, const URL& aURL )
330 throw ( RuntimeException )
331 {
332 	(void)xControl;
333 	(void)aURL;
334 }
335 
336 bool
337 ScriptProtocolHandler::getScriptInvocation()
338 {
339     if ( !m_xScriptInvocation.is() && m_xFrame.is() )
340     {
341         Reference< XController > xController = m_xFrame->getController();
342         if ( xController .is() )
343         {
344             // try to obtain an XScriptInvocationContext interface, preferred from the
345             // mode, then from the controller
346             if ( !m_xScriptInvocation.set( xController->getModel(), UNO_QUERY ) )
347                 m_xScriptInvocation.set( xController, UNO_QUERY );
348         }
349     }
350     return m_xScriptInvocation.is();
351 }
352 
353 void ScriptProtocolHandler::createScriptProvider()
354 {
355     if ( m_xScriptProvider.is() )
356         return;
357 
358     try
359     {
360         // first, ask the component supporting the XScriptInvocationContext interface
361         // (if there is one) for a script provider
362         if ( getScriptInvocation() )
363         {
364             Reference< XScriptProviderSupplier > xSPS( m_xScriptInvocation, UNO_QUERY );
365             if ( xSPS.is() )
366                 m_xScriptProvider = xSPS->getScriptProvider();
367         }
368 
369         // second, ask the model in our frame
370         if ( !m_xScriptProvider.is() && m_xFrame.is() )
371         {
372             Reference< XController > xController = m_xFrame->getController();
373             if ( xController .is() )
374             {
375                 Reference< XScriptProviderSupplier > xSPS( xController->getModel(), UNO_QUERY );
376                 if ( xSPS.is() )
377                     m_xScriptProvider = xSPS->getScriptProvider();
378             }
379         }
380 
381 
382         // as a fallback, ask the controller
383         if ( !m_xScriptProvider.is() && m_xFrame.is() )
384         {
385             Reference< XScriptProviderSupplier > xSPS( m_xFrame->getController(), UNO_QUERY );
386             if ( xSPS.is() )
387                 m_xScriptProvider = xSPS->getScriptProvider();
388         }
389 
390         // if nothing of this is successful, use the master script provider
391         if ( !m_xScriptProvider.is() )
392         {
393             Reference< XPropertySet > xProps( m_xFactory, UNO_QUERY_THROW );
394 
395             ::rtl::OUString dc(
396                 RTL_CONSTASCII_USTRINGPARAM( "DefaultContext" ) );
397 
398             Reference< XComponentContext > xCtx(
399                 xProps->getPropertyValue( dc ), UNO_QUERY_THROW );
400 
401             ::rtl::OUString tmspf = ::rtl::OUString::createFromAscii(
402                 "/singletons/com.sun.star.script.provider.theMasterScriptProviderFactory");
403 
404             Reference< provider::XScriptProviderFactory > xFac(
405                 xCtx->getValueByName( tmspf ), UNO_QUERY_THROW );
406 
407             Any aContext;
408             if ( getScriptInvocation() )
409                 aContext = makeAny( m_xScriptInvocation );
410             m_xScriptProvider = Reference< provider::XScriptProvider > (
411                 xFac->createScriptProvider( aContext ), UNO_QUERY_THROW );
412         }
413     }
414     catch ( RuntimeException & e )
415     {
416         ::rtl::OUString temp = OUSTR( "ScriptProtocolHandler::createScriptProvider(),  " );
417         throw RuntimeException( temp.concat( e.Message ), Reference< XInterface >() );
418     }
419     catch ( Exception & e )
420     {
421         ::rtl::OUString temp = OUSTR( "ScriptProtocolHandler::createScriptProvider: " );
422         throw RuntimeException( temp.concat( e.Message ), Reference< XInterface >() );
423     }
424 }
425 
426 ScriptProtocolHandler::ScriptProtocolHandler(
427 Reference< css::lang::XMultiServiceFactory > const& rFact ) :
428 m_bInitialised( false ), m_xFactory( rFact )
429 {
430 }
431 
432 ScriptProtocolHandler::~ScriptProtocolHandler()
433 {
434 }
435 
436 /* XServiceInfo */
437 ::rtl::OUString SAL_CALL ScriptProtocolHandler::getImplementationName( )
438 throw( RuntimeException )
439 {
440     return impl_getStaticImplementationName();
441 }
442 
443 /* XServiceInfo */
444 sal_Bool SAL_CALL ScriptProtocolHandler::supportsService(
445 const ::rtl::OUString& sServiceName )
446 throw( RuntimeException )
447 {
448     Sequence< ::rtl::OUString > seqServiceNames = getSupportedServiceNames();
449     const ::rtl::OUString* pArray = seqServiceNames.getConstArray();
450     for ( sal_Int32 nCounter = 0; nCounter < seqServiceNames.getLength(); nCounter++ )
451     {
452         if ( pArray[ nCounter ] == sServiceName )
453         {
454             return sal_True ;
455         }
456     }
457 
458     return sal_False ;
459 }
460 
461 /* XServiceInfo */
462 Sequence< ::rtl::OUString > SAL_CALL ScriptProtocolHandler::getSupportedServiceNames()
463 throw( RuntimeException )
464 {
465     return impl_getStaticSupportedServiceNames();
466 }
467 
468 /* Helper for XServiceInfo */
469 Sequence< ::rtl::OUString > ScriptProtocolHandler::impl_getStaticSupportedServiceNames()
470 {
471     ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
472     Sequence< ::rtl::OUString > seqServiceNames( 1 );
473     seqServiceNames.getArray() [ 0 ] =
474         ::rtl::OUString::createFromAscii( ::scripting_protocolhandler::MYSERVICENAME );
475     return seqServiceNames ;
476 }
477 
478 /* Helper for XServiceInfo */
479 ::rtl::OUString ScriptProtocolHandler::impl_getStaticImplementationName()
480 {
481     return ::rtl::OUString::createFromAscii( ::scripting_protocolhandler::MYIMPLNAME );
482 }
483 
484 /* Helper for registry */
485 Reference< XInterface > SAL_CALL ScriptProtocolHandler::impl_createInstance(
486 const Reference< css::lang::XMultiServiceFactory >& xServiceManager )
487 throw( RuntimeException )
488 {
489     return Reference< XInterface > ( *new ScriptProtocolHandler( xServiceManager ) );
490 }
491 
492 /* Factory for registration */
493 Reference< XSingleServiceFactory > ScriptProtocolHandler::impl_createFactory(
494 const Reference< XMultiServiceFactory >& xServiceManager )
495 {
496     Reference< XSingleServiceFactory > xReturn (
497         cppu::createSingleFactory( xServiceManager,
498             ScriptProtocolHandler::impl_getStaticImplementationName(),
499             ScriptProtocolHandler::impl_createInstance,
500             ScriptProtocolHandler::impl_getStaticSupportedServiceNames() )
501     );
502     return xReturn;
503 }
504 
505 } // namespace scripting_protocolhandler
506 
507 /* exported functions for registration */
508 extern "C"
509 {
510 
511 #undef css
512 #define css ::com::sun::star
513 
514     void SAL_CALL component_getImplementationEnvironment(
515         const sal_Char** ppEnvironmentTypeName, uno_Environment** ppEnvironment )
516     {
517 		(void)ppEnvironment;
518 
519         *ppEnvironmentTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME ;
520     }
521 
522     void* SAL_CALL component_getFactory( const sal_Char * pImplementationName ,
523                                          void * pServiceManager ,
524                                          void * pRegistryKey )
525     {
526 		(void)pRegistryKey;
527 
528         // Set default return value for this operation - if it failed.
529         void * pReturn = NULL ;
530 
531         if (
532             ( pImplementationName != NULL ) &&
533             ( pServiceManager != NULL )
534         )
535         {
536             // Define variables which are used in following macros.
537             ::com::sun::star::uno::Reference<
538             ::com::sun::star::lang::XSingleServiceFactory > xFactory ;
539             ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >
540             xServiceManager( reinterpret_cast<
541             ::com::sun::star::lang::XMultiServiceFactory* >( pServiceManager ) ) ;
542 
543             if ( ::scripting_protocolhandler::ScriptProtocolHandler::impl_getStaticImplementationName().equals(
544                 ::rtl::OUString::createFromAscii( pImplementationName ) ) )
545             {
546                 xFactory = ::scripting_protocolhandler::ScriptProtocolHandler::impl_createFactory( xServiceManager );
547             }
548 
549             // Factory is valid - service was found.
550             if ( xFactory.is() )
551             {
552                 xFactory->acquire();
553                 pReturn = xFactory.get();
554             }
555         }
556 
557         // Return with result of this operation.
558         return pReturn ;
559     }
560 } // extern "C"
561 
562 
563