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 
initialize(const css::uno::Sequence<css::uno::Any> & aArguments)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 
queryDispatch(const URL & aURL,const::rtl::OUString & sTargetFrameName,sal_Int32 nSearchFlags)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
queryDispatches(const Sequence<DispatchDescriptor> & seqDescriptor)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 
dispatchWithNotification(const URL & aURL,const Sequence<PropertyValue> & lArgs,const Reference<XDispatchResultListener> & xListener)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 
158     if ( m_bInitialised )
159     {
160         try
161         {
162             ::rtl::OUString xStringUri = ::rtl::Uri::decode( aURL.Complete,
163                 rtl_UriDecodeWithCharset, RTL_TEXTENCODING_UTF8 );
164             bool bIsDocumentScript = ( xStringUri.indexOfAsciiL( RTL_CONSTASCII_STRINGPARAM( "document" ) ) !=-1 );
165 
166             if ( bIsDocumentScript )
167             {
168                 // obtain the component for our security check
169                 Reference< XEmbeddedScripts > xDocumentScripts;
170                 if ( getScriptInvocation() )
171                     xDocumentScripts.set( m_xScriptInvocation->getScriptContainer(), UNO_SET_THROW );
172 
173                 OSL_ENSURE( xDocumentScripts.is(), "ScriptProtocolHandler::dispatchWithNotification: can't do the security check!" );
174                 if ( !xDocumentScripts.is() || !xDocumentScripts->getAllowMacroExecution() )
175                     return;
176             }
177 
178             // Creates a ScriptProvider ( if one is not created allready )
179             createScriptProvider();
180 
181             Reference< provider::XScript > xFunc =
182                 m_xScriptProvider->getScript( aURL.Complete );
183             ENSURE_OR_THROW( xFunc.is(),
184                 "ScriptProtocolHandler::dispatchWithNotification: validate xFunc - unable to obtain XScript interface" );
185 
186 
187             Sequence< Any > inArgs( 0 );
188             Sequence< Any > outArgs( 0 );
189             Sequence< sal_Int16 > outIndex;
190 
191             if ( lArgs.getLength() > 0 )
192             {
193                int argCount = 0;
194                for ( int index = 0; index < lArgs.getLength(); index++ )
195                {
196                    // Sometimes we get a propertyval with name = "Referer"
197                    // this is not an argument to be passed to script, so
198                    // ignore.
199                    if ( lArgs[ index ].Name.compareToAscii("Referer") != 0  ||
200                         lArgs[ index ].Name.getLength() == 0 )
201                    {
202                        inArgs.realloc( ++argCount );
203                        inArgs[ argCount - 1 ] = lArgs[ index ].Value;
204                    }
205                }
206             }
207 
208             // attempt to protect the document against the script tampering with its Undo Context
209             ::std::auto_ptr< ::framework::DocumentUndoGuard > pUndoGuard;
210             if ( bIsDocumentScript )
211                 pUndoGuard.reset( new ::framework::DocumentUndoGuard( m_xScriptInvocation ) );
212 
213             bSuccess = sal_False;
214             while ( !bSuccess )
215             {
216                 Any aFirstCaughtException;
217                 try
218                 {
219                     invokeResult = xFunc->invoke( inArgs, outIndex, outArgs );
220                     bSuccess = sal_True;
221                 }
222                 catch( const provider::ScriptFrameworkErrorException& se )
223                 {
224                     if  ( !aFirstCaughtException.hasValue() )
225                         aFirstCaughtException = ::cppu::getCaughtException();
226 
227                     if ( se.errorType != provider::ScriptFrameworkErrorType::NO_SUCH_SCRIPT )
228                         // the only condition which allows us to retry is if there is no method with the
229                         // given name/signature
230                         ::cppu::throwException( aFirstCaughtException );
231 
232                     if ( inArgs.getLength() == 0 )
233                         // no chance to retry if we can't strip more in-args
234                         ::cppu::throwException( aFirstCaughtException );
235 
236                     // strip one argument, then retry
237                     inArgs.realloc( inArgs.getLength() - 1 );
238                 }
239             }
240         }
241         // Office doesn't handle exceptions rethrown here very well, it cores,
242         // all we can is log them and then set fail for the dispatch event!
243         // (if there is a listener of course)
244         catch ( const Exception & e )
245         {
246             aException = ::cppu::getCaughtException();
247 
248             ::rtl::OUString reason = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "ScriptProtocolHandler::dispatch: caught " ) );
249 
250             invokeResult <<= reason.concat( aException.getValueTypeName() ).concat( e.Message );
251 
252 			bCaughtException = sal_True;
253         }
254     }
255     else
256     {
257         ::rtl::OUString reason = ::rtl::OUString::createFromAscii(
258         "ScriptProtocolHandler::dispatchWithNotification failed, ScriptProtocolHandler not initialised"
259         );
260         invokeResult <<= reason;
261     }
262 
263 	if ( bCaughtException )
264 	{
265 		SfxAbstractDialogFactory* pFact = SfxAbstractDialogFactory::Create();
266 
267 		if ( pFact != NULL )
268 		{
269 			VclAbstractDialog* pDlg =
270 				pFact->CreateScriptErrorDialog( NULL, aException );
271 
272 			if ( pDlg != NULL )
273 			{
274 				pDlg->Execute();
275 				delete pDlg;
276 			}
277 		}
278    	}
279 
280     if ( xListener.is() )
281     {
282         // always call dispatchFinished(), because we didn't load a document but
283         // executed a macro instead!
284         ::com::sun::star::frame::DispatchResultEvent aEvent;
285 
286         aEvent.Source = static_cast< ::cppu::OWeakObject* >( this );
287         aEvent.Result = invokeResult;
288         if ( bSuccess )
289         {
290             aEvent.State = ::com::sun::star::frame::DispatchResultState::SUCCESS;
291         }
292         else
293         {
294             aEvent.State = ::com::sun::star::frame::DispatchResultState::FAILURE;
295         }
296 
297         try
298         {
299             xListener->dispatchFinished( aEvent ) ;
300         }
301         catch(RuntimeException & e)
302         {
303             OSL_TRACE(
304             "ScriptProtocolHandler::dispatchWithNotification: caught RuntimeException"
305             "while dispatchFinished %s",
306             ::rtl::OUStringToOString( e.Message,
307             RTL_TEXTENCODING_ASCII_US ).pData->buffer );
308         }
309     }
310 }
311 
dispatch(const URL & aURL,const Sequence<PropertyValue> & lArgs)312 void SAL_CALL ScriptProtocolHandler::dispatch(
313 const URL& aURL, const Sequence< PropertyValue >& lArgs )
314 throw ( RuntimeException )
315 {
316     dispatchWithNotification( aURL, lArgs, Reference< XDispatchResultListener >() );
317 }
318 
addStatusListener(const Reference<XStatusListener> & xControl,const URL & aURL)319 void SAL_CALL ScriptProtocolHandler::addStatusListener(
320 const Reference< XStatusListener >& xControl, const URL& aURL )
321 throw ( RuntimeException )
322 {
323 	(void)xControl;
324 	(void)aURL;
325 
326     // implement if status is supported
327 }
328 
removeStatusListener(const Reference<XStatusListener> & xControl,const URL & aURL)329 void SAL_CALL ScriptProtocolHandler::removeStatusListener(
330 const Reference< XStatusListener >& xControl, const URL& aURL )
331 throw ( RuntimeException )
332 {
333 	(void)xControl;
334 	(void)aURL;
335 }
336 
337 bool
getScriptInvocation()338 ScriptProtocolHandler::getScriptInvocation()
339 {
340     if ( !m_xScriptInvocation.is() && m_xFrame.is() )
341     {
342         Reference< XController > xController = m_xFrame->getController();
343         if ( xController .is() )
344         {
345             // try to obtain an XScriptInvocationContext interface, preferred from the
346             // mode, then from the controller
347             if ( !m_xScriptInvocation.set( xController->getModel(), UNO_QUERY ) )
348                 m_xScriptInvocation.set( xController, UNO_QUERY );
349         }
350     }
351     return m_xScriptInvocation.is();
352 }
353 
createScriptProvider()354 void ScriptProtocolHandler::createScriptProvider()
355 {
356     if ( m_xScriptProvider.is() )
357         return;
358 
359     try
360     {
361         // first, ask the component supporting the XScriptInvocationContext interface
362         // (if there is one) for a script provider
363         if ( getScriptInvocation() )
364         {
365             Reference< XScriptProviderSupplier > xSPS( m_xScriptInvocation, UNO_QUERY );
366             if ( xSPS.is() )
367                 m_xScriptProvider = xSPS->getScriptProvider();
368         }
369 
370         // second, ask the model in our frame
371         if ( !m_xScriptProvider.is() && m_xFrame.is() )
372         {
373             Reference< XController > xController = m_xFrame->getController();
374             if ( xController .is() )
375             {
376                 Reference< XScriptProviderSupplier > xSPS( xController->getModel(), UNO_QUERY );
377                 if ( xSPS.is() )
378                     m_xScriptProvider = xSPS->getScriptProvider();
379             }
380         }
381 
382 
383         // as a fallback, ask the controller
384         if ( !m_xScriptProvider.is() && m_xFrame.is() )
385         {
386             Reference< XScriptProviderSupplier > xSPS( m_xFrame->getController(), UNO_QUERY );
387             if ( xSPS.is() )
388                 m_xScriptProvider = xSPS->getScriptProvider();
389         }
390 
391         // if nothing of this is successful, use the master script provider
392         if ( !m_xScriptProvider.is() )
393         {
394             Reference< XPropertySet > xProps( m_xFactory, UNO_QUERY_THROW );
395 
396             ::rtl::OUString dc(
397                 RTL_CONSTASCII_USTRINGPARAM( "DefaultContext" ) );
398 
399             Reference< XComponentContext > xCtx(
400                 xProps->getPropertyValue( dc ), UNO_QUERY_THROW );
401 
402             ::rtl::OUString tmspf = ::rtl::OUString::createFromAscii(
403                 "/singletons/com.sun.star.script.provider.theMasterScriptProviderFactory");
404 
405             Reference< provider::XScriptProviderFactory > xFac(
406                 xCtx->getValueByName( tmspf ), UNO_QUERY_THROW );
407 
408             Any aContext;
409             if ( getScriptInvocation() )
410                 aContext = makeAny( m_xScriptInvocation );
411             m_xScriptProvider = Reference< provider::XScriptProvider > (
412                 xFac->createScriptProvider( aContext ), UNO_QUERY_THROW );
413         }
414     }
415     catch ( RuntimeException & e )
416     {
417         ::rtl::OUString temp = OUSTR( "ScriptProtocolHandler::createScriptProvider(),  " );
418         throw RuntimeException( temp.concat( e.Message ), Reference< XInterface >() );
419     }
420     catch ( Exception & e )
421     {
422         ::rtl::OUString temp = OUSTR( "ScriptProtocolHandler::createScriptProvider: " );
423         throw RuntimeException( temp.concat( e.Message ), Reference< XInterface >() );
424     }
425 }
426 
ScriptProtocolHandler(Reference<css::lang::XMultiServiceFactory> const & rFact)427 ScriptProtocolHandler::ScriptProtocolHandler(
428 Reference< css::lang::XMultiServiceFactory > const& rFact ) :
429 m_bInitialised( false ), m_xFactory( rFact )
430 {
431 }
432 
~ScriptProtocolHandler()433 ScriptProtocolHandler::~ScriptProtocolHandler()
434 {
435 }
436 
437 /* XServiceInfo */
getImplementationName()438 ::rtl::OUString SAL_CALL ScriptProtocolHandler::getImplementationName( )
439 throw( RuntimeException )
440 {
441     return impl_getStaticImplementationName();
442 }
443 
444 /* XServiceInfo */
supportsService(const::rtl::OUString & sServiceName)445 sal_Bool SAL_CALL ScriptProtocolHandler::supportsService(
446 const ::rtl::OUString& sServiceName )
447 throw( RuntimeException )
448 {
449     Sequence< ::rtl::OUString > seqServiceNames = getSupportedServiceNames();
450     const ::rtl::OUString* pArray = seqServiceNames.getConstArray();
451     for ( sal_Int32 nCounter = 0; nCounter < seqServiceNames.getLength(); nCounter++ )
452     {
453         if ( pArray[ nCounter ] == sServiceName )
454         {
455             return sal_True ;
456         }
457     }
458 
459     return sal_False ;
460 }
461 
462 /* XServiceInfo */
getSupportedServiceNames()463 Sequence< ::rtl::OUString > SAL_CALL ScriptProtocolHandler::getSupportedServiceNames()
464 throw( RuntimeException )
465 {
466     return impl_getStaticSupportedServiceNames();
467 }
468 
469 /* Helper for XServiceInfo */
impl_getStaticSupportedServiceNames()470 Sequence< ::rtl::OUString > ScriptProtocolHandler::impl_getStaticSupportedServiceNames()
471 {
472     ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
473     Sequence< ::rtl::OUString > seqServiceNames( 1 );
474     seqServiceNames.getArray() [ 0 ] =
475         ::rtl::OUString::createFromAscii( ::scripting_protocolhandler::MYSERVICENAME );
476     return seqServiceNames ;
477 }
478 
479 /* Helper for XServiceInfo */
impl_getStaticImplementationName()480 ::rtl::OUString ScriptProtocolHandler::impl_getStaticImplementationName()
481 {
482     return ::rtl::OUString::createFromAscii( ::scripting_protocolhandler::MYIMPLNAME );
483 }
484 
485 /* Helper for registry */
impl_createInstance(const Reference<css::lang::XMultiServiceFactory> & xServiceManager)486 Reference< XInterface > SAL_CALL ScriptProtocolHandler::impl_createInstance(
487 const Reference< css::lang::XMultiServiceFactory >& xServiceManager )
488 throw( RuntimeException )
489 {
490     return Reference< XInterface > ( *new ScriptProtocolHandler( xServiceManager ) );
491 }
492 
493 /* Factory for registration */
impl_createFactory(const Reference<XMultiServiceFactory> & xServiceManager)494 Reference< XSingleServiceFactory > ScriptProtocolHandler::impl_createFactory(
495 const Reference< XMultiServiceFactory >& xServiceManager )
496 {
497     Reference< XSingleServiceFactory > xReturn (
498         cppu::createSingleFactory( xServiceManager,
499             ScriptProtocolHandler::impl_getStaticImplementationName(),
500             ScriptProtocolHandler::impl_createInstance,
501             ScriptProtocolHandler::impl_getStaticSupportedServiceNames() )
502     );
503     return xReturn;
504 }
505 
506 } // namespace scripting_protocolhandler
507 
508 /* exported functions for registration */
509 extern "C"
510 {
511 
512 #undef css
513 #define css ::com::sun::star
514 
component_getImplementationEnvironment(const sal_Char ** ppEnvironmentTypeName,uno_Environment ** ppEnvironment)515     void SAL_CALL component_getImplementationEnvironment(
516         const sal_Char** ppEnvironmentTypeName, uno_Environment** ppEnvironment )
517     {
518 		(void)ppEnvironment;
519 
520         *ppEnvironmentTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME ;
521     }
522 
component_getFactory(const sal_Char * pImplementationName,void * pServiceManager,void * pRegistryKey)523     void* SAL_CALL component_getFactory( const sal_Char * pImplementationName ,
524                                          void * pServiceManager ,
525                                          void * pRegistryKey )
526     {
527 		(void)pRegistryKey;
528 
529         // Set default return value for this operation - if it failed.
530         void * pReturn = NULL ;
531 
532         if (
533             ( pImplementationName != NULL ) &&
534             ( pServiceManager != NULL )
535         )
536         {
537             // Define variables which are used in following macros.
538             ::com::sun::star::uno::Reference<
539             ::com::sun::star::lang::XSingleServiceFactory > xFactory ;
540             ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >
541             xServiceManager( reinterpret_cast<
542             ::com::sun::star::lang::XMultiServiceFactory* >( pServiceManager ) ) ;
543 
544             if ( ::scripting_protocolhandler::ScriptProtocolHandler::impl_getStaticImplementationName().equals(
545                 ::rtl::OUString::createFromAscii( pImplementationName ) ) )
546             {
547                 xFactory = ::scripting_protocolhandler::ScriptProtocolHandler::impl_createFactory( xServiceManager );
548             }
549 
550             // Factory is valid - service was found.
551             if ( xFactory.is() )
552             {
553                 xFactory->acquire();
554                 pReturn = xFactory.get();
555             }
556         }
557 
558         // Return with result of this operation.
559         return pReturn ;
560     }
561 } // extern "C"
562 
563 
564