Debian Codegraph @

basic/source/uno/scriptcont.cxx

raw
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3 * This file is part of the LibreOffice project.
4 *
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
8 *
9 * This file incorporates work covered by the following license notice:
10 *
11 * Licensed to the Apache Software Foundation (ASF) under one or more
12 * contributor license agreements. See the NOTICE file distributed
13 * with this work for additional information regarding copyright
14 * ownership. The ASF licenses this file to you under the Apache
15 * License, Version 2.0 (the "License"); you may not use this file
16 * except in compliance with the License. You may obtain a copy of
17 * the License at http://www.apache.org/licenses/LICENSE-2.0 .
18 */
19
20 #include <scriptcont.hxx>
21 #include <com/sun/star/packages/WrongPasswordException.hpp>
22 #include <com/sun/star/xml/sax/Parser.hpp>
23 #include <com/sun/star/xml/sax/InputSource.hpp>
24 #include <com/sun/star/xml/sax/Writer.hpp>
25 #include <com/sun/star/io/XTruncate.hpp>
26 #include <com/sun/star/embed/ElementModes.hpp>
27 #include <com/sun/star/embed/XEncryptionProtectedSource.hpp>
28 #include <com/sun/star/beans/XPropertySet.hpp>
29 #include <com/sun/star/embed/XTransactedObject.hpp>
30 #include <com/sun/star/task/ErrorCodeIOException.hpp>
31 #include <com/sun/star/script/ModuleType.hpp>
32 #include <com/sun/star/lang/XMultiServiceFactory.hpp>
33 #include <comphelper/storagehelper.hxx>
34 #include <unotools/ucbstreamhelper.hxx>
35 #include <osl/diagnose.h>
36 #include <sal/log.hxx>
37 #include <sot/storage.hxx>
38
39 // For password functionality
40 #include <tools/urlobj.hxx>
41
42 #include <o3tl/temporary.hxx>
43 #include <svtools/sfxecode.hxx>
44 #include <svtools/ehdl.hxx>
45 #include <basic/basmgr.hxx>
46 #include <basic/sbmod.hxx>
47 #include <basic/modsizeexceeded.hxx>
48 #include <xmlscript/xmlmod_imexp.hxx>
49 #include <com/sun/star/util/VetoException.hpp>
50 #include <memory>
51
52 namespace basic
53 {
54
55 using namespace com::sun::star::container;
56 using namespace com::sun::star::io;
57 using namespace com::sun::star::uno;
58 using namespace com::sun::star::ucb;
59 using namespace com::sun::star::lang;
60 using namespace com::sun::star::script;
61 using namespace com::sun::star::xml::sax;
62 using namespace com::sun::star;
63 using namespace cppu;
64
65
66 // Implementation class SfxScriptLibraryContainer
67
68 OUString SfxScriptLibraryContainer::getInfoFileName() const
69 {
70 static constexpr OUStringLiteral script = u"script";
71 return script;
72 }
73 OUString SfxScriptLibraryContainer::getOldInfoFileName() const
74 {
75 static constexpr OUStringLiteral script = u"script";
76 return script;
77 }
78 OUString SfxScriptLibraryContainer::getLibElementFileExtension() const
79 {
80 static constexpr OUStringLiteral xba = u"xba";
81 return xba;
82 }
83 OUString SfxScriptLibraryContainer::getLibrariesDir() const
84 {
85 static constexpr OUStringLiteral sBasic = u"Basic";
86 return sBasic;
87 }
88
89 void SfxScriptLibraryContainer::setLibraryPassword( const OUString& rLibraryName, const OUString& rPassword )
90 {
91 try
92 {
93 SfxLibrary* pImplLib = getImplLib( rLibraryName );
94 if( !rPassword.isEmpty() )
95 {
96 pImplLib->mbDoc50Password = true;
97 pImplLib->mbPasswordProtected = true;
98 pImplLib->maPassword = rPassword;
99 SfxScriptLibrary *const pSL(dynamic_cast<SfxScriptLibrary *>(pImplLib));
100 if (pSL && pSL->mbLoaded)
101 {
102 pSL->mbLoadedSource = true; // must store source code now!
103 }
104 }
105 }
106 catch(const NoSuchElementException& ) {}
107 }
108
109 // Ctor for service
110 SfxScriptLibraryContainer::SfxScriptLibraryContainer()
111 {
112 // all initialisation has to be done
113 // by calling XInitialization::initialize
114 }
115
116 SfxScriptLibraryContainer::SfxScriptLibraryContainer( const uno::Reference< embed::XStorage >& xStorage )
117 {
118 init(OUString(), xStorage, o3tl::temporary(std::unique_lock(m_aMutex)));
119 }
120
121 // Methods to get library instances of the correct type
122 rtl::Reference<SfxLibrary> SfxScriptLibraryContainer::implCreateLibrary( const OUString& )
123 {
124 return new SfxScriptLibrary( maModifiable, mxSFI );
125 }
126
127 rtl::Reference<SfxLibrary> SfxScriptLibraryContainer::implCreateLibraryLink( const OUString&,
128 const OUString& aLibInfoFileURL,
129 const OUString& StorageURL,
130 bool ReadOnly )
131 {
132 return new SfxScriptLibrary( maModifiable, mxSFI,
133 aLibInfoFileURL, StorageURL, ReadOnly );
134 }
135
136 Any SfxScriptLibraryContainer::createEmptyLibraryElement()
137 {
138 Any aRetAny;
139 aRetAny <<= OUString();
140 return aRetAny;
141 }
142
143 bool SfxScriptLibraryContainer::isLibraryElementValid(const Any& rElement) const
144 {
145 return SfxScriptLibrary::containsValidModule(rElement);
146 }
147
148 void SfxScriptLibraryContainer::writeLibraryElement( const Reference < XNameContainer >& xLib,
149 const OUString& aElementName,
150 const Reference< XOutputStream >& xOutput)
151 {
152 // Create sax writer
153 Reference< XWriter > xWriter = xml::sax::Writer::create(mxContext);
154
155 Reference< XTruncate > xTruncate( xOutput, UNO_QUERY );
156 OSL_ENSURE( xTruncate.is(), "Currently only the streams that can be truncated are expected!" );
157 if ( xTruncate.is() )
158 {
159 xTruncate->truncate();
160 }
161 xWriter->setOutputStream( xOutput );
162
163 xmlscript::ModuleDescriptor aMod;
164 aMod.aName = aElementName;
165 aMod.aLanguage = "StarBasic";
166 Any aElement = xLib->getByName( aElementName );
167 aElement >>= aMod.aCode;
168
169 Reference< script::vba::XVBAModuleInfo > xModInfo( xLib, UNO_QUERY );
170 if( xModInfo.is() && xModInfo->hasModuleInfo( aElementName ) )
171 {
172 script::ModuleInfo aModInfo = xModInfo->getModuleInfo( aElementName );
173 switch( aModInfo.ModuleType )
174 {
175 case ModuleType::NORMAL:
176 aMod.aModuleType = "normal";
177 break;
178 case ModuleType::CLASS:
179 aMod.aModuleType ="class";
180 break;
181 case ModuleType::FORM:
182 aMod.aModuleType = "form";
183 break;
184 case ModuleType::DOCUMENT:
185 aMod.aModuleType = "document";
186 break;
187 case ModuleType::UNKNOWN:
188 // nothing
189 break;
190 }
191 }
192
193 xmlscript::exportScriptModule( xWriter, aMod );
194 }
195
196
197 Any SfxScriptLibraryContainer::importLibraryElement
198 ( const Reference < XNameContainer >& xLib,
199 const OUString& aElementName, const OUString& aFile,
200 const uno::Reference< io::XInputStream >& xInStream )
201 {
202 Any aRetAny;
203
204 Reference< XParser > xParser = xml::sax::Parser::create( mxContext );
205
206 // Read from storage?
207 bool bStorage = xInStream.is();
208 Reference< XInputStream > xInput;
209
210 if( bStorage )
211 {
212 xInput = xInStream;
213 }
214 else
215 {
216 try
217 {
218 xInput = mxSFI->openFileRead( aFile );
219 }
220 catch(const Exception& )
221 //catch( Exception& e )
222 {
223 // TODO:
224 //throw WrappedTargetException( e );
225 }
226 }
227
228 if( !xInput.is() )
229 return aRetAny;
230
231 InputSource source;
232 source.aInputStream = std::move(xInput);
233 source.sSystemId = aFile;
234
235 // start parsing
236 xmlscript::ModuleDescriptor aMod;
237
238 try
239 {
240 xParser->setDocumentHandler( ::xmlscript::importScriptModule( aMod ) );
241 xParser->parseStream( source );
242 }
243 catch(const Exception& )
244 {
245 SfxErrorContext aEc( ERRCTX_SFX_LOADBASIC, aFile );
246 ErrorHandler::HandleError( ERRCODE_IO_GENERAL );
247 }
248
249 aRetAny <<= aMod.aCode;
250
251 // TODO: Check language
252 // aMod.aLanguage
253 // aMod.aName ignored
254 if( !aMod.aModuleType.isEmpty() )
255 {
256 /* If in VBA compatibility mode, force creation of the VBA Globals
257 object. Each application will create an instance of its own
258 implementation and store it in its Basic manager. Implementations
259 will do all necessary additional initialization, such as
260 registering the global "This***Doc" UNO constant, starting the
261 document events processor etc.
262 */
263 if( getVBACompatibilityMode() ) try
264 {
265 Reference< frame::XModel > xModel( mxOwnerDocument ); // weak-ref -> ref
266 Reference< XMultiServiceFactory > xFactory( xModel, UNO_QUERY_THROW );
267 xFactory->createInstance(u"ooo.vba.VBAGlobals"_ustr);
268 }
269 catch(const Exception& )
270 {
271 }
272
273 script::ModuleInfo aModInfo;
274 aModInfo.ModuleType = ModuleType::UNKNOWN;
275 if( aMod.aModuleType == "normal" )
276 {
277 aModInfo.ModuleType = ModuleType::NORMAL;
278 }
279 else if( aMod.aModuleType == "class" )
280 {
281 aModInfo.ModuleType = ModuleType::CLASS;
282 }
283 else if( aMod.aModuleType == "form" )
284 {
285 aModInfo.ModuleType = ModuleType::FORM;
286 aModInfo.ModuleObject = mxOwnerDocument;
287 }
288 else if( aMod.aModuleType == "document" )
289 {
290 aModInfo.ModuleType = ModuleType::DOCUMENT;
291
292 // #163691# use the same codename access instance for all document modules
293 if( !mxCodeNameAccess.is() ) try
294 {
295 Reference<frame::XModel > xModel( mxOwnerDocument );
296 Reference< XMultiServiceFactory> xSF( xModel, UNO_QUERY_THROW );
297 mxCodeNameAccess.set( xSF->createInstance(u"ooo.vba.VBAObjectModuleObjectProvider"_ustr), UNO_QUERY );
298 }
299 catch(const Exception& ) {}
300
301 if( mxCodeNameAccess.is() )
302 {
303 try
304 {
305 aModInfo.ModuleObject.set( mxCodeNameAccess->getByName( aElementName), uno::UNO_QUERY );
306 }
307 catch(const uno::Exception&)
308 {
309 SAL_WARN("basic", "Failed to get document object for " << aElementName );
310 }
311 }
312 }
313
314 Reference< script::vba::XVBAModuleInfo > xVBAModuleInfo( xLib, UNO_QUERY );
315 if( xVBAModuleInfo.is() )
316 {
317 if( xVBAModuleInfo->hasModuleInfo( aElementName ) )
318 {
319 xVBAModuleInfo->removeModuleInfo( aElementName );
320 }
321 xVBAModuleInfo->insertModuleInfo( aElementName, aModInfo );
322 }
323 }
324
325 return aRetAny;
326 }
327
328 rtl::Reference<SfxLibraryContainer> SfxScriptLibraryContainer::createInstanceImpl()
329 {
330 return new SfxScriptLibraryContainer();
331 }
332
333 void SfxScriptLibraryContainer::importFromOldStorage( const OUString& aFile )
334 {
335 // TODO: move loading from old storage to binary filters?
336 rtl::Reference<SotStorage> xStorage(new SotStorage(false, aFile));
337 if( xStorage->GetError() == ERRCODE_NONE )
338 {
339 BasicManager aBasicManager( *xStorage, aFile );
340
341 // Set info
342 LibraryContainerInfo aInfo( this, nullptr, this );
343 aBasicManager.SetLibraryContainerInfo( aInfo );
344 }
345 }
346
347
348 // Storing with password encryption
349
350 // Methods XLibraryContainerPassword
351 sal_Bool SAL_CALL SfxScriptLibraryContainer::isLibraryPasswordProtected( const OUString& Name )
352 {
353 LibraryContainerMethodGuard aGuard( *this );
354 SfxLibrary* pImplLib = getImplLib( Name );
355 bool bRet = pImplLib->mbPasswordProtected;
356 return bRet;
357 }
358
359 sal_Bool SAL_CALL SfxScriptLibraryContainer::isLibraryPasswordVerified( const OUString& Name )
360 {
361 LibraryContainerMethodGuard aGuard( *this );
362 SfxLibrary* pImplLib = getImplLib( Name );
363 if( !pImplLib->mbPasswordProtected )
364 {
365 throw IllegalArgumentException(u"!passwordProtected"_ustr, getXWeak(), 1);
366 }
367 bool bRet = pImplLib->mbPasswordVerified;
368 return bRet;
369 }
370
371 sal_Bool SAL_CALL SfxScriptLibraryContainer::verifyLibraryPassword
372 ( const OUString& Name, const OUString& Password )
373 {
374 LibraryContainerMethodGuard aGuard( *this );
375 std::unique_lock guard(m_aMutex);
376 SfxLibrary* pImplLib = getImplLib( Name );
377 if( !pImplLib->mbPasswordProtected || pImplLib->mbPasswordVerified )
378 {
379 throw IllegalArgumentException(u"!PasswordProtected || PasswordVerified"_ustr, getXWeak(), 1);
380 }
381 // Test password
382 bool bSuccess = false;
383 if( pImplLib->mbDoc50Password )
384 {
385 bSuccess = ( Password == pImplLib->maPassword );
386 if( bSuccess )
387 {
388 pImplLib->mbPasswordVerified = true;
389 }
390 }
391 else
392 {
393 pImplLib->maPassword = Password;
394 bSuccess = implLoadPasswordLibrary( pImplLib, Name, true, guard);
395 if( bSuccess )
396 {
397 // The library gets modified by verifying the password, because other-
398 // wise for saving the storage would be copied and that doesn't work
399 // with mtg's storages when the password is verified
400 pImplLib->implSetModified(true, guard);
401 pImplLib->mbPasswordVerified = true;
402
403 // Reload library to get source
404 if( pImplLib->mbLoaded )
405 {
406 implLoadPasswordLibrary( pImplLib, Name, false, guard);
407 }
408 }
409 }
410 return bSuccess;
411 }
412
413 void SAL_CALL SfxScriptLibraryContainer::changeLibraryPassword( const OUString& Name,
414 const OUString& OldPassword,
415 const OUString& NewPassword )
416 {
417 LibraryContainerMethodGuard aGuard( *this );
418 SfxLibrary* pImplLib = getImplLib( Name );
419 if( OldPassword == NewPassword )
420 {
421 return;
422 }
423 bool bOldPassword = !OldPassword.isEmpty();
424 bool bNewPassword = !NewPassword.isEmpty();
425 bool bStorage = mxStorage.is() && !pImplLib->mbLink;
426
427 if( pImplLib->mbReadOnly || (bOldPassword && !pImplLib->mbPasswordProtected) )
428 {
429 throw IllegalArgumentException();
430 }
431 // Library must be loaded
432 loadLibrary( Name );
433
434 bool bKillCryptedFiles = false;
435 bool bKillUnencryptedFiles = false;
436
437 // Remove or change password?
438 if( bOldPassword )
439 {
440 if( isLibraryPasswordVerified( Name ) )
441 {
442 if( pImplLib->maPassword != OldPassword )
443 {
444 throw IllegalArgumentException();
445 }
446 }
447 else
448 {
449 if( !verifyLibraryPassword( Name, OldPassword ) )
450 {
451 throw IllegalArgumentException();
452 }
453 // Reload library to get source
454 // Should be done in verifyLibraryPassword loadLibrary( Name );
455 }
456
457 if( !bNewPassword )
458 {
459 pImplLib->mbPasswordProtected = false;
460 pImplLib->mbPasswordVerified = false;
461 pImplLib->maPassword.clear();
462
463 std::unique_lock guard(m_aMutex);
464 maModifiable.setModified(true, guard);
465 pImplLib->implSetModified(true, guard);
466
467 if( !bStorage && !pImplLib->mbDoc50Password )
468 {
469 // Store application basic unencrypted
470 uno::Reference< embed::XStorage > xStorage;
471 storeLibraries_Impl(xStorage, false, guard);
472 bKillCryptedFiles = true;
473 }
474 }
475 }
476
477 // Set new password?
478 if( bNewPassword )
479 {
480 pImplLib->mbPasswordProtected = true;
481 pImplLib->mbPasswordVerified = true;
482 pImplLib->maPassword = NewPassword;
483 SfxScriptLibrary *const pSL(dynamic_cast<SfxScriptLibrary *>(pImplLib));
484 if (pSL && pSL->mbLoaded)
485 {
486 pSL->mbLoadedSource = true; // must store source code now!
487 }
488
489 std::unique_lock guard(m_aMutex);
490 maModifiable.setModified(true, guard);
491 pImplLib->implSetModified(true, guard);
492
493 if( !bStorage && !pImplLib->mbDoc50Password )
494 {
495 // Store application basic crypted
496 uno::Reference< embed::XStorage > xStorage;
497 storeLibraries_Impl(xStorage, false, guard);
498 bKillUnencryptedFiles = true;
499 }
500 }
501
502 if( !(bKillCryptedFiles || bKillUnencryptedFiles) )
503 return;
504
505 Sequence< OUString > aElementNames = pImplLib->getElementNames();
506 sal_Int32 nNameCount = aElementNames.getLength();
507 const OUString* pNames = aElementNames.getConstArray();
508 OUString aLibDirPath = createAppLibraryFolder( pImplLib, Name );
509 try
510 {
511 for( sal_Int32 i = 0 ; i < nNameCount ; i++ )
512 {
513 OUString aElementName = pNames[ i ];
514
515 INetURLObject aElementInetObj( aLibDirPath );
516 aElementInetObj.insertName( aElementName, false,
517 INetURLObject::LAST_SEGMENT,
518 INetURLObject::EncodeMechanism::All );
519 if( bKillUnencryptedFiles )
520 {
521 aElementInetObj.setExtension( maLibElementFileExtension );
522 }
523 else
524 {
525 aElementInetObj.setExtension( u"pba" );
526 }
527 OUString aElementPath( aElementInetObj.GetMainURL( INetURLObject::DecodeMechanism::NONE ) );
528
529 if( mxSFI->exists( aElementPath ) )
530 {
531 mxSFI->kill( aElementPath );
532 }
533 }
534 }
535 catch(const Exception& ) {}
536 }
537
538
539 static void setStreamKey( const uno::Reference< io::XStream >& xStream, const OUString& aPass )
540 {
541 uno::Reference< embed::XEncryptionProtectedSource > xEncrStream( xStream, uno::UNO_QUERY );
542 if ( xEncrStream.is() )
543 {
544 xEncrStream->setEncryptionPassword( aPass );
545 }
546 }
547
548
549 // Impl methods
550 bool SfxScriptLibraryContainer::implStorePasswordLibrary( SfxLibrary* pLib,
551 const OUString& aName,
552 const uno::Reference< embed::XStorage >& xStorage,
553 const css::uno::Reference< css::task::XInteractionHandler >& xHandler )
554 {
555 Reference< XSimpleFileAccess3 > xDummySFA;
556 return implStorePasswordLibrary( pLib, aName, xStorage, OUString(), xDummySFA, xHandler );
557 }
558
559 bool SfxScriptLibraryContainer::implStorePasswordLibrary( SfxLibrary* pLib, const OUString& aName,
560 const css::uno::Reference< css::embed::XStorage >& xStorage,
561 const OUString& aTargetURL,
562 const Reference< XSimpleFileAccess3 >& rToUseSFI,
563 const css::uno::Reference< css::task::XInteractionHandler >& xHandler )
564 {
565 bool bExport = !aTargetURL.isEmpty();
566
567 BasicManager* pBasicMgr = getBasicManager();
568 OSL_ENSURE( pBasicMgr, "SfxScriptLibraryContainer::implStorePasswordLibrary: cannot do this without a BasicManager!" );
569 if ( !pBasicMgr )
570 {
571 return false;
572 }
573 // Only need to handle the export case here,
574 // save/saveas etc are handled in sfxbasemodel::storeSelf &
575 // sfxbasemodel::impl_store
576 std::vector<OUString> aNames;
577 if ( bExport && pBasicMgr->ImgVersion12PsswdBinaryLimitExceeded(aNames) )
578 {
579 if ( xHandler.is() )
580 {
581 rtl::Reference<ModuleSizeExceeded> pReq = new ModuleSizeExceeded( aNames );
582 xHandler->handle( pReq );
583 if ( pReq->isAbort() )
584 {
585 throw util::VetoException();
586 }
587 }
588 }
589
590 StarBASIC* pBasicLib = pBasicMgr->GetLib( aName );
591 if( !pBasicLib )
592 {
593 return false;
594 }
595 Sequence< OUString > aElementNames = pLib->getElementNames();
596 sal_Int32 nNameCount = aElementNames.getLength();
597 const OUString* pNames = aElementNames.getConstArray();
598
599 bool bLink = pLib->mbLink;
600 bool bStorage = xStorage.is() && !bLink;
601 if( bStorage )
602 {
603 for( sal_Int32 i = 0 ; i < nNameCount ; i++ )
604 {
605 OUString aElementName = pNames[ i ];
606
607 // Write binary image stream
608 SbModule* pMod = pBasicLib->FindModule( aElementName );
609 if( pMod )
610 {
611 OUString aCodeStreamName = aElementName + ".bin";
612 try
613 {
614 uno::Reference< io::XStream > xCodeStream = xStorage->openStreamElement(
615 aCodeStreamName,
616 embed::ElementModes::READWRITE | embed::ElementModes::TRUNCATE );
617
618 if ( !xCodeStream.is() )
619 {
620 throw uno::RuntimeException(u"null returned from openStreamElement"_ustr);
621 }
622 SvMemoryStream aMemStream;
623 /*sal_Bool bStore = */pMod->StoreBinaryData( aMemStream );
624
625 sal_Int32 const nSize = aMemStream.Tell();
626 if (nSize < 0) { abort(); }
627 Sequence< sal_Int8 > aBinSeq( nSize );
628 sal_Int8* pData = aBinSeq.getArray();
629 memcpy( pData, aMemStream.GetData(), nSize );
630
631 Reference< XOutputStream > xOut = xCodeStream->getOutputStream();
632 if ( !xOut.is() )
633 {
634 throw io::IOException(); // access denied because the stream is readonly
635 }
636 xOut->writeBytes( aBinSeq );
637 xOut->closeOutput();
638 }
639 catch(const uno::Exception& )
640 {
641 // TODO: handle error
642 }
643 }
644
645 if( pLib->mbPasswordVerified || pLib->mbDoc50Password )
646 {
647 if( !isLibraryElementValid( pLib->getByName( aElementName ) ) )
648 {
649 SAL_WARN( "basic", "invalid library element '" << aElementName << "'.");
650 continue;
651 }
652
653 OUString aSourceStreamName = aElementName + ".xml";
654 try
655 {
656 uno::Reference< io::XStream > xSourceStream = xStorage->openStreamElement(
657 aSourceStreamName,
658 embed::ElementModes::READWRITE );
659 uno::Reference< beans::XPropertySet > xProps( xSourceStream, uno::UNO_QUERY_THROW );
660 xProps->setPropertyValue(u"MediaType"_ustr, uno::Any( u"text/xml"_ustr ) );
661
662 // Set encryption key
663 setStreamKey( xSourceStream, pLib->maPassword );
664
665 Reference< XOutputStream > xOutput = xSourceStream->getOutputStream();
666 Reference< XNameContainer > xLib( pLib );
667 writeLibraryElement( xLib, aElementName, xOutput );
668 }
669 catch(const uno::Exception& )
670 {
671 OSL_FAIL( "Problem on storing of password library!" );
672 // TODO: error handling
673 }
674 }
675 else // !mbPasswordVerified
676 {
677 // TODO
678 // What to do if not verified?! In any case it's already loaded here
679 }
680 }
681
682 }
683 // Application libraries have only to be saved if the password
684 // is verified because otherwise they can't be modified
685 else if( pLib->mbPasswordVerified || bExport )
686 {
687 try
688 {
689 Reference< XSimpleFileAccess3 > xSFI = mxSFI;
690 if( rToUseSFI.is() )
691 {
692 xSFI = rToUseSFI;
693 }
694 OUString aLibDirPath;
695 if( bExport )
696 {
697 INetURLObject aInetObj( aTargetURL );
698 aInetObj.insertName( aName, true, INetURLObject::LAST_SEGMENT,
699 INetURLObject::EncodeMechanism::All );
700 aLibDirPath = aInetObj.GetMainURL( INetURLObject::DecodeMechanism::NONE );
701
702 if( !xSFI->isFolder( aLibDirPath ) )
703 {
704 xSFI->createFolder( aLibDirPath );
705 }
706 }
707 else
708 {
709 aLibDirPath = createAppLibraryFolder( pLib, aName );
710 }
711
712 for( sal_Int32 i = 0 ; i < nNameCount ; i++ )
713 {
714 OUString aElementName = pNames[ i ];
715
716 INetURLObject aElementInetObj( aLibDirPath );
717 aElementInetObj.insertName( aElementName, false,
718 INetURLObject::LAST_SEGMENT,
719 INetURLObject::EncodeMechanism::All );
720 aElementInetObj.setExtension( u"pba" );
721 OUString aElementPath = aElementInetObj.GetMainURL( INetURLObject::DecodeMechanism::NONE );
722
723 if( !isLibraryElementValid( pLib->getByName( aElementName ) ) )
724 {
725 SAL_WARN( "basic", "invalid library element '" << aElementName << "'.");
726 continue;
727 }
728
729 try
730 {
731 uno::Reference< embed::XStorage > xElementRootStorage =
732 ::comphelper::OStorageHelper::GetStorageFromURL(
733 aElementPath,
734 embed::ElementModes::READWRITE );
735 if ( !xElementRootStorage.is() )
736 {
737 throw uno::RuntimeException(u"null returned from GetStorageFromURL"_ustr);
738 }
739 // Write binary image stream
740 SbModule* pMod = pBasicLib->FindModule( aElementName );
741 if( pMod )
742 {
743 uno::Reference< io::XStream > xCodeStream = xElementRootStorage->openStreamElement(
744 u"code.bin"_ustr,
745 embed::ElementModes::WRITE | embed::ElementModes::TRUNCATE );
746
747 SvMemoryStream aMemStream;
748 /*sal_Bool bStore = */pMod->StoreBinaryData( aMemStream );
749
750 sal_Int32 const nSize = aMemStream.Tell();
751 if (nSize < 0) { abort(); }
752 Sequence< sal_Int8 > aBinSeq( nSize );
753 sal_Int8* pData = aBinSeq.getArray();
754 memcpy( pData, aMemStream.GetData(), nSize );
755
756 Reference< XOutputStream > xOut = xCodeStream->getOutputStream();
757 if ( xOut.is() )
758 {
759 xOut->writeBytes( aBinSeq );
760 xOut->closeOutput();
761 }
762 }
763
764 // Write encrypted source stream
765 OUString aSourceStreamName( u"source.xml"_ustr );
766
767 uno::Reference< io::XStream > xSourceStream;
768 try
769 {
770 xSourceStream = xElementRootStorage->openStreamElement(
771 aSourceStreamName,
772 embed::ElementModes::WRITE | embed::ElementModes::TRUNCATE );
773
774 // #87671 Allow encryption
775 uno::Reference< embed::XEncryptionProtectedSource > xEncr( xSourceStream, uno::UNO_QUERY_THROW );
776 xEncr->setEncryptionPassword( pLib->maPassword );
777 }
778 catch(const css::packages::WrongPasswordException& )
779 {
780 xSourceStream = xElementRootStorage->openEncryptedStreamElement(
781 aSourceStreamName,
782 embed::ElementModes::WRITE | embed::ElementModes::TRUNCATE,
783 pLib->maPassword );
784 }
785
786 uno::Reference< beans::XPropertySet > xProps( xSourceStream, uno::UNO_QUERY_THROW );
787 xProps->setPropertyValue(u"MediaType"_ustr, uno::Any( u"text/xml"_ustr ) );
788
789 Reference< XOutputStream > xOut = xSourceStream->getOutputStream();
790 Reference< XNameContainer > xLib( pLib );
791 writeLibraryElement( xLib, aElementName, xOut );
792 // i50568: sax writer already closes stream
793 // xOut->closeOutput();
794
795 uno::Reference< embed::XTransactedObject > xTransact( xElementRootStorage, uno::UNO_QUERY_THROW );
796 xTransact->commit();
797 }
798 catch(const uno::Exception& )
799 {
800 // TODO: handle error
801 }
802
803 }
804 }
805 catch(const Exception& )
806 {
807 }
808 }
809 return true;
810 }
811
812 bool SfxScriptLibraryContainer::implLoadPasswordLibrary
813 ( SfxLibrary* pLib, const OUString& Name, bool bVerifyPasswordOnly, std::unique_lock<std::mutex>& guard )
814 {
815 bool bRet = true;
816
817 bool bLink = pLib->mbLink;
818 bool bStorage = mxStorage.is() && !bLink;
819
820 // Already loaded? Then only verifiedPassword can change something
821 SfxScriptLibrary* pScriptLib = static_cast< SfxScriptLibrary* >( pLib );
822 if( pScriptLib->mbLoaded )
823 {
824 if( pScriptLib->mbLoadedBinary && !bVerifyPasswordOnly &&
825 (pScriptLib->mbLoadedSource || !pLib->mbPasswordVerified) )
826 {
827 return false;
828 }
829 }
830
831 StarBASIC* pBasicLib = nullptr;
832 bool bLoadBinary = false;
833 if( !pScriptLib->mbLoadedBinary && !bVerifyPasswordOnly && !pLib->mbPasswordVerified )
834 {
835 BasicManager* pBasicMgr = getBasicManager();
836 OSL_ENSURE( pBasicMgr, "SfxScriptLibraryContainer::implLoadPasswordLibrary: cannot do this without a BasicManager!" );
837 bool bLoaded = pScriptLib->mbLoaded;
838 pScriptLib->mbLoaded = true; // Necessary to get lib
839 pBasicLib = pBasicMgr ? pBasicMgr->GetLib( Name ) : nullptr;
840 pScriptLib->mbLoaded = bLoaded; // Restore flag
841 if( !pBasicLib )
842 {
843 return false;
844 }
845 bLoadBinary = true;
846 pScriptLib->mbLoadedBinary = true;
847 }
848
849 bool bLoadSource = false;
850 if( !pScriptLib->mbLoadedSource && pLib->mbPasswordVerified && !bVerifyPasswordOnly )
851 {
852 bLoadSource = true;
853 pScriptLib->mbLoadedSource = true;
854 }
855
856 Sequence< OUString > aElementNames = pLib->getElementNames();
857 sal_Int32 nNameCount = aElementNames.getLength();
858 const OUString* pNames = aElementNames.getConstArray();
859
860 if( bStorage )
861 {
862 uno::Reference< embed::XStorage > xLibrariesStor;
863 uno::Reference< embed::XStorage > xLibraryStor;
864 try {
865 xLibrariesStor = mxStorage->openStorageElement( maLibrariesDir, embed::ElementModes::READ );
866 if ( !xLibrariesStor.is() )
867 {
868 throw uno::RuntimeException(u"null returned from openStorageElement"_ustr);
869 }
870 xLibraryStor = xLibrariesStor->openStorageElement( Name, embed::ElementModes::READ );
871 if ( !xLibraryStor.is() )
872 {
873 throw uno::RuntimeException(u"null returned from openStorageElement"_ustr);
874 }
875 }
876 catch(const uno::Exception& )
877 {
878 OSL_FAIL( "### couldn't open sub storage for library" );
879 return false;
880 }
881
882 for( sal_Int32 i = 0 ; i < nNameCount ; i++ )
883 {
884 OUString aElementName = pNames[ i ];
885
886 // Load binary
887 if( bLoadBinary )
888 {
889 SbModule* pMod = pBasicLib->FindModule( aElementName );
890 if( !pMod )
891 {
892 pMod = pBasicLib->MakeModule( aElementName, OUString() );
893 pBasicLib->SetModified( false );
894 }
895
896 OUString aCodeStreamName= aElementName + ".bin";
897 try
898 {
899 uno::Reference< io::XStream > xCodeStream = xLibraryStor->openStreamElement(
900 aCodeStreamName,
901 embed::ElementModes::READ );
902 if ( !xCodeStream.is() )
903 {
904 throw uno::RuntimeException(u"null returned from openStreamElement"_ustr);
905 }
906 std::unique_ptr<SvStream> pStream(::utl::UcbStreamHelper::CreateStream( xCodeStream ));
907 if ( !pStream || pStream->GetError() )
908 {
909 sal_uInt32 nError = sal_uInt32(pStream ? pStream->GetError() : ERRCODE_IO_GENERAL);
910 throw task::ErrorCodeIOException(
911 ("utl::UcbStreamHelper::CreateStream failed for \""
912 + aCodeStreamName + "\": 0x"
913 + OUString::number(nError, 16)),
914 uno::Reference< uno::XInterface >(), nError);
915 }
916
917 /*sal_Bool bRet = */pMod->LoadBinaryData( *pStream );
918 // TODO: Check return value
919 }
920 catch(const uno::Exception& )
921 {
922 // TODO: error handling
923 }
924 }
925
926 // Load source
927 if( bLoadSource || bVerifyPasswordOnly )
928 {
929 // Access encrypted source stream
930 OUString aSourceStreamName = aElementName + ".xml";
931 try
932 {
933 uno::Reference< io::XStream > xSourceStream = xLibraryStor->openEncryptedStreamElement(
934 aSourceStreamName,
935 embed::ElementModes::READ,
936 pLib->maPassword );
937 if ( !xSourceStream.is() )
938 {
939 throw uno::RuntimeException(u"null returned from openEncryptedStreamElement"_ustr);
940 }
941 // if this point is reached then the password is correct
942 if ( !bVerifyPasswordOnly )
943 {
944 uno::Reference< io::XInputStream > xInStream = xSourceStream->getInputStream();
945 if ( !xInStream.is() )
946 {
947 throw io::IOException(); // read access denied, seems to be impossible
948 }
949 Reference< XNameContainer > xLib( pLib );
950 Any aAny = importLibraryElement( xLib,
951 aElementName, aSourceStreamName,
952 xInStream );
953 if( pLib->hasByName( aElementName ) )
954 {
955 if( aAny.hasValue() )
956 {
957 pLib->maNameContainer.replaceByName(aElementName, aAny, guard);
958 }
959 }
960 else
961 {
962 pLib->maNameContainer.insertByName(aElementName, aAny, guard);
963 }
964 }
965 }
966 catch(const uno::Exception& )
967 {
968 bRet = false;
969 }
970 }
971 }
972 }
973 else
974 {
975 try
976 {
977 OUString aLibDirPath = createAppLibraryFolder( pLib, Name );
978
979 for( sal_Int32 i = 0 ; i < nNameCount ; i++ )
980 {
981 OUString aElementName = pNames[ i ];
982
983 INetURLObject aElementInetObj( aLibDirPath );
984 aElementInetObj.insertName( aElementName, false,
985 INetURLObject::LAST_SEGMENT, INetURLObject::EncodeMechanism::All );
986 aElementInetObj.setExtension( u"pba" );
987 OUString aElementPath = aElementInetObj.GetMainURL( INetURLObject::DecodeMechanism::NONE );
988
989 uno::Reference< embed::XStorage > xElementRootStorage;
990 try
991 {
992 xElementRootStorage = ::comphelper::OStorageHelper::GetStorageFromURL(
993 aElementPath,
994 embed::ElementModes::READ );
995 } catch(const uno::Exception& )
996 {
997 // TODO: error handling
998 }
999
1000 if ( xElementRootStorage.is() )
1001 {
1002 // Load binary
1003 if( bLoadBinary )
1004 {
1005 SbModule* pMod = pBasicLib->FindModule( aElementName );
1006 if( !pMod )
1007 {
1008 pMod = pBasicLib->MakeModule( aElementName, OUString() );
1009 pBasicLib->SetModified( false );
1010 }
1011
1012 try
1013 {
1014 uno::Reference< io::XStream > xCodeStream = xElementRootStorage->openStreamElement(
1015 u"code.bin"_ustr,
1016 embed::ElementModes::READ );
1017
1018 std::unique_ptr<SvStream> pStream(::utl::UcbStreamHelper::CreateStream( xCodeStream ));
1019 if ( !pStream || pStream->GetError() )
1020 {
1021 sal_uInt32 nError = sal_uInt32(pStream ? pStream->GetError() : ERRCODE_IO_GENERAL);
1022 throw task::ErrorCodeIOException(
1023 ("utl::UcbStreamHelper::CreateStream failed"
1024 " for code.bin: 0x"
1025 + OUString::number(nError, 16)),
1026 uno::Reference< uno::XInterface >(),
1027 nError);
1028 }
1029
1030 /*sal_Bool bRet = */pMod->LoadBinaryData( *pStream );
1031 // TODO: Check return value
1032 }
1033 catch(const uno::Exception& )
1034 {
1035 // TODO: error handling
1036 }
1037 }
1038
1039 // Load source
1040 if( bLoadSource || bVerifyPasswordOnly )
1041 {
1042 // Access encrypted source stream
1043 try
1044 {
1045 OUString aSourceStreamName( u"source.xml"_ustr );
1046 uno::Reference< io::XStream > xSourceStream = xElementRootStorage->openEncryptedStreamElement(
1047 aSourceStreamName,
1048 embed::ElementModes::READ,
1049 pLib->maPassword );
1050 if ( !xSourceStream.is() )
1051 {
1052 throw uno::RuntimeException(u"null returned from openEncryptedStreamElement"_ustr);
1053 }
1054 if ( !bVerifyPasswordOnly )
1055 {
1056 uno::Reference< io::XInputStream > xInStream = xSourceStream->getInputStream();
1057 if ( !xInStream.is() )
1058 {
1059 throw io::IOException(); // read access denied, seems to be impossible
1060 }
1061 Reference< XNameContainer > xLib( pLib );
1062 Any aAny = importLibraryElement( xLib,
1063 aElementName,
1064 aSourceStreamName,
1065 xInStream );
1066 if( pLib->hasByName( aElementName ) )
1067 {
1068 if( aAny.hasValue() )
1069 {
1070 pLib->maNameContainer.replaceByName(aElementName, aAny,
1071 guard);
1072 }
1073 }
1074 else
1075 {
1076 pLib->maNameContainer.insertByName(aElementName, aAny, guard);
1077 }
1078 }
1079 }
1080 catch (const uno::Exception& )
1081 {
1082 bRet = false;
1083 }
1084 }
1085 }
1086 }
1087 }
1088 catch(const Exception& )
1089 {
1090 // TODO
1091 //throw e;
1092 }
1093 }
1094
1095 return bRet;
1096 }
1097
1098
1099 void SfxScriptLibraryContainer::onNewRootStorage()
1100 {
1101 }
1102
1103 sal_Bool SAL_CALL SfxScriptLibraryContainer:: HasExecutableCode( const OUString& Library )
1104 {
1105 BasicManager* pBasicMgr = getBasicManager();
1106 OSL_ENSURE( pBasicMgr, "we need a basicmanager, really we do" );
1107 if ( pBasicMgr )
1108 {
1109 return pBasicMgr->HasExeCode( Library ); // need to change this to take name
1110 }
1111 // default to it has code if we can't decide
1112 return true;
1113 }
1114
1115
1116 // Service
1117 OUString SAL_CALL SfxScriptLibraryContainer::getImplementationName( )
1118 {
1119 return u"com.sun.star.comp.sfx2.ScriptLibraryContainer"_ustr;
1120 }
1121
1122 Sequence< OUString > SAL_CALL SfxScriptLibraryContainer::getSupportedServiceNames( )
1123 {
1124 return {u"com.sun.star.script.DocumentScriptLibraryContainer"_ustr,
1125 u"com.sun.star.script.ScriptLibraryContainer"_ustr}; // for compatibility
1126 }
1127
1128 // Implementation class SfxScriptLibrary
1129
1130 // Ctor
1131 SfxScriptLibrary::SfxScriptLibrary( ModifiableHelper& _rModifiable,
1132 const Reference< XSimpleFileAccess3 >& xSFI )
1133 : SfxScriptLibrary_BASE(_rModifiable, cppu::UnoType<OUString>::get(), xSFI)
1134 , mbLoadedSource( false )
1135 , mbLoadedBinary( false )
1136 {
1137 }
1138
1139 SfxScriptLibrary::SfxScriptLibrary( ModifiableHelper& _rModifiable,
1140 const Reference< XSimpleFileAccess3 >& xSFI,
1141 const OUString& aLibInfoFileURL,
1142 const OUString& aStorageURL,
1143 bool ReadOnly )
1144 : SfxScriptLibrary_BASE(_rModifiable, cppu::UnoType<OUString>::get(), xSFI,
1145 aLibInfoFileURL, aStorageURL, ReadOnly)
1146 , mbLoadedSource( false )
1147 , mbLoadedBinary( false )
1148 {
1149 }
1150
1151 bool SfxScriptLibrary::isLoadedStorable()
1152 {
1153 // note: mbLoadedSource can only be true for password-protected lib!
1154 return SfxLibrary::isLoadedStorable() && (!isPasswordProtected() || mbLoadedSource);
1155 }
1156
1157 // Provide modify state including resources
1158 bool SfxScriptLibrary::isModified()
1159 {
1160 return implIsModified(); // No resources
1161 }
1162
1163 void SfxScriptLibrary::storeResources()
1164 {
1165 // No resources
1166 }
1167
1168 void SfxScriptLibrary::storeResourcesToURL( const OUString&,
1169 const Reference< task::XInteractionHandler >& )
1170 {}
1171
1172 void SfxScriptLibrary::storeResourcesAsURL
1173 ( const OUString&, const OUString& )
1174 {}
1175
1176 void SfxScriptLibrary::storeResourcesToStorage( const css::uno::Reference
1177 < css::embed::XStorage >& )
1178 {
1179 // No resources
1180 }
1181
1182 bool SfxScriptLibrary::containsValidModule(const Any& rElement)
1183 {
1184 OUString sModuleText;
1185 rElement >>= sModuleText;
1186 return ( !sModuleText.isEmpty() );
1187 }
1188
1189 bool SfxScriptLibrary::isLibraryElementValid(const css::uno::Any& rElement) const
1190 {
1191 return SfxScriptLibrary::containsValidModule(rElement);
1192 }
1193
1194 script::ModuleInfo SAL_CALL SfxScriptLibrary::getModuleInfo( const OUString& ModuleName )
1195 {
1196 if ( !hasModuleInfo( ModuleName ) )
1197 {
1198 throw NoSuchElementException();
1199 }
1200 return mModuleInfo[ ModuleName ];
1201 }
1202
1203 sal_Bool SAL_CALL SfxScriptLibrary::hasModuleInfo( const OUString& ModuleName )
1204 {
1205 return mModuleInfo.contains(ModuleName);
1206 }
1207
1208 void SAL_CALL SfxScriptLibrary::insertModuleInfo( const OUString& ModuleName, const script::ModuleInfo& ModuleInfo )
1209 {
1210 if ( hasModuleInfo( ModuleName ) )
1211 {
1212 throw ElementExistException();
1213 }
1214 mModuleInfo[ ModuleName ] = ModuleInfo;
1215 }
1216
1217 void SAL_CALL SfxScriptLibrary::removeModuleInfo( const OUString& ModuleName )
1218 {
1219 // #FIXME add NoSuchElementException to the spec
1220 if ( mModuleInfo.erase( ModuleName ) == 0 )
1221 throw NoSuchElementException();
1222 }
1223
1224 } // namespace basic
1225
1226
1227 extern "C" SAL_DLLPUBLIC_EXPORT css::uno::XInterface*
1228 com_sun_star_comp_sfx2_ScriptLibraryContainer_get_implementation(css::uno::XComponentContext*,
1229 css::uno::Sequence<css::uno::Any> const &)
1230 {
1231 return cppu::acquire(new basic::SfxScriptLibraryContainer());
1232 }
1233
1234
1235 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */