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