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