1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
3 * This file is part of the LibreOffice project.
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/.
9 * This file incorporates work covered by the following license notice:
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 .
20 #include <config_fuzzers.h>
22 #include "mdrivermanager.hxx"
23 #include <com/sun/star/configuration/theDefaultProvider.hpp>
24 #include <com/sun/star/sdbc/XDriver.hpp>
25 #include <com/sun/star/container/XContentEnumerationAccess.hpp>
26 #include <com/sun/star/container/ElementExistException.hpp>
27 #include <com/sun/star/beans/NamedValue.hpp>
28 #include <com/sun/star/logging/LogLevel.hpp>
30 #include <comphelper/diagnose_ex.hxx>
31 #include <cppuhelper/implbase.hxx>
32 #include <cppuhelper/supportsservice.hxx>
33 #include <cppuhelper/weak.hxx>
34 #include <osl/diagnose.h>
41 namespace drivermanager
44 using namespace ::com::sun::star::uno
;
45 using namespace ::com::sun::star::lang
;
46 using namespace ::com::sun::star::sdbc
;
47 using namespace ::com::sun::star::beans
;
48 using namespace ::com::sun::star::container
;
49 using namespace ::com::sun::star::logging
;
50 using namespace ::osl
;
52 constexpr OUStringLiteral SERVICE_SDBC_DRIVER
= u
"com.sun.star.sdbc.Driver";
54 /// @throws NoSuchElementException
55 static void throwNoSuchElementException()
57 throw NoSuchElementException();
60 class ODriverEnumeration
: public ::cppu::WeakImplHelper
< XEnumeration
>
62 friend class OSDBCDriverManager
;
64 typedef std::vector
< Reference
< XDriver
> > DriverArray
;
65 DriverArray m_aDrivers
;
66 DriverArray::const_iterator m_aPos
;
70 virtual ~ODriverEnumeration() override
;
72 explicit ODriverEnumeration(DriverArray
&& _rDriverSequence
);
75 virtual sal_Bool SAL_CALL
hasMoreElements( ) override
;
76 virtual Any SAL_CALL
nextElement( ) override
;
80 ODriverEnumeration::ODriverEnumeration(DriverArray
&& _rDriverSequence
)
81 :m_aDrivers( std::move(_rDriverSequence
) )
82 ,m_aPos( m_aDrivers
.begin() )
87 ODriverEnumeration::~ODriverEnumeration()
92 sal_Bool SAL_CALL
ODriverEnumeration::hasMoreElements( )
94 return m_aPos
!= m_aDrivers
.end();
98 Any SAL_CALL
ODriverEnumeration::nextElement( )
100 if ( !hasMoreElements() )
101 throwNoSuchElementException();
103 return Any( *m_aPos
++ );
108 /// an STL functor which ensures that a SdbcDriver described by a DriverAccess is loaded
111 explicit EnsureDriver( const Reference
< XComponentContext
> &rxContext
)
112 : mxContext( rxContext
) {}
114 const DriverAccess
& operator()( const DriverAccess
& _rDescriptor
) const
116 // we did not load this driver, yet
117 if (_rDescriptor
.xDriver
.is())
120 // we have a factory for it
121 if (_rDescriptor
.xComponentFactory
.is())
123 DriverAccess
& rDesc
= const_cast<DriverAccess
&>(_rDescriptor
);
128 rDesc
.xComponentFactory
->createInstanceWithContext(mxContext
), css::uno::UNO_QUERY
);
130 catch (const Exception
&)
132 //failure, abandon driver
133 rDesc
.xComponentFactory
.clear();
140 Reference
< XComponentContext
> mxContext
;
143 /// an STL functor which extracts a SdbcDriver from a DriverAccess
144 struct ExtractDriverFromAccess
146 const Reference
<XDriver
>& operator()( const DriverAccess
& _rAccess
) const
148 return _rAccess
.xDriver
;
152 struct ExtractDriverFromCollectionElement
154 const Reference
<XDriver
>& operator()( const DriverCollection::value_type
& _rElement
) const
156 return _rElement
.second
;
160 // predicate for checking whether or not a driver accepts a given URL
161 bool AcceptsURL( const OUString
& _rURL
, const Reference
<XDriver
>& _rDriver
)
164 return _rDriver
.is() && _rDriver
->acceptsURL( _rURL
);
168 sal_Int32
lcl_getDriverPrecedence( const Reference
<XComponentContext
>& _rContext
, Sequence
< OUString
>& _rPrecedence
)
170 _rPrecedence
.realloc( 0 );
173 // create a configuration provider
174 Reference
< XMultiServiceFactory
> xConfigurationProvider(
175 css::configuration::theDefaultProvider::get( _rContext
) );
177 // one argument for creating the node access: the path to the configuration node
178 Sequence
< Any
> aCreationArgs
{ Any(NamedValue(
179 "nodepath", Any( OUString("org.openoffice.Office.DataAccess/DriverManager") ) )) };
181 // create the node access
182 Reference
< XNameAccess
> xDriverManagerNode(
183 xConfigurationProvider
->createInstanceWithArguments("com.sun.star.configuration.ConfigurationAccess", aCreationArgs
),
186 OSL_ENSURE(xDriverManagerNode
.is(), "lcl_getDriverPrecedence: could not open my configuration node!");
187 if (xDriverManagerNode
.is())
189 // obtain the preference list
190 Any aPreferences
= xDriverManagerNode
->getByName("DriverPrecedence");
191 bool bSuccess
= aPreferences
>>= _rPrecedence
;
192 OSL_ENSURE(bSuccess
|| !aPreferences
.hasValue(), "lcl_getDriverPrecedence: invalid value for the preferences node (no string sequence but not NULL)!");
195 catch( const Exception
& )
197 DBG_UNHANDLED_EXCEPTION("connectivity.manager");
200 return _rPrecedence
.getLength();
204 /// an STL algorithm compatible predicate comparing two DriverAccess instances by their implementation names
205 struct CompareDriverAccessByName
208 bool operator()( const DriverAccess
& lhs
, const DriverAccess
& rhs
)
210 return lhs
.sImplementationName
< rhs
.sImplementationName
;
214 /// and an STL algorithm compatible predicate comparing the impl name of a DriverAccess to a string
215 struct EqualDriverAccessToName
217 OUString m_sImplName
;
218 explicit EqualDriverAccessToName(OUString _sImplName
) : m_sImplName(std::move(_sImplName
)){}
220 bool operator()( const DriverAccess
& lhs
)
222 return lhs
.sImplementationName
== m_sImplName
;
227 OSDBCDriverManager::OSDBCDriverManager( const Reference
< XComponentContext
>& _rxContext
)
228 :OSDBCDriverManager_Base(m_aMutex
)
229 ,m_xContext( _rxContext
)
230 ,m_aEventLogger( _rxContext
, "org.openoffice.logging.sdbc.DriverManager" )
231 ,m_aDriverConfig(m_xContext
)
234 // bootstrap all objects supporting the .sdb.Driver service
237 // initialize the drivers order
238 initializeDriverPrecedence();
242 OSDBCDriverManager::~OSDBCDriverManager()
246 void OSDBCDriverManager::bootstrapDrivers()
248 Reference
< XContentEnumerationAccess
> xEnumAccess( m_xContext
->getServiceManager(), UNO_QUERY
);
249 Reference
< XEnumeration
> xEnumDrivers
;
250 if (xEnumAccess
.is())
251 xEnumDrivers
= xEnumAccess
->createContentEnumeration(SERVICE_SDBC_DRIVER
);
253 OSL_ENSURE( xEnumDrivers
.is(), "OSDBCDriverManager::bootstrapDrivers: no enumeration for the drivers available!" );
254 if (!xEnumDrivers
.is())
257 Reference
< XSingleComponentFactory
> xFactory
;
258 Reference
< XServiceInfo
> xSI
;
259 while (xEnumDrivers
->hasMoreElements())
261 xFactory
.set(xEnumDrivers
->nextElement(), css::uno::UNO_QUERY
);
262 OSL_ENSURE( xFactory
.is(), "OSDBCDriverManager::bootstrapDrivers: no factory extracted" );
266 // we got a factory for the driver
267 DriverAccess aDriverDescriptor
;
268 bool bValidDescriptor
= false;
270 // can it tell us something about the implementation name?
271 xSI
.set(xFactory
, css::uno::UNO_QUERY
);
273 { // yes -> no need to load the driver immediately (load it later when needed)
274 aDriverDescriptor
.sImplementationName
= xSI
->getImplementationName();
275 aDriverDescriptor
.xComponentFactory
= xFactory
;
276 bValidDescriptor
= true;
278 m_aEventLogger
.log( LogLevel::CONFIG
,
279 "found SDBC driver $1$, no need to load it",
280 aDriverDescriptor
.sImplementationName
285 // no -> create the driver
286 Reference
< XDriver
> xDriver( xFactory
->createInstanceWithContext( m_xContext
), UNO_QUERY
);
287 OSL_ENSURE( xDriver
.is(), "OSDBCDriverManager::bootstrapDrivers: a driver which is no driver?!" );
291 aDriverDescriptor
.xDriver
= xDriver
;
292 // and obtain its implementation name
293 xSI
.set(xDriver
, css::uno::UNO_QUERY
);
294 OSL_ENSURE( xSI
.is(), "OSDBCDriverManager::bootstrapDrivers: a driver without service info?" );
297 aDriverDescriptor
.sImplementationName
= xSI
->getImplementationName();
298 bValidDescriptor
= true;
300 m_aEventLogger
.log( LogLevel::CONFIG
,
301 "found SDBC driver $1$, needed to load it",
302 aDriverDescriptor
.sImplementationName
308 if ( bValidDescriptor
)
310 m_aDriversBS
.push_back( aDriverDescriptor
);
317 void OSDBCDriverManager::initializeDriverPrecedence()
320 if ( m_aDriversBS
.empty() )
326 // get the precedence of the drivers from the configuration
327 Sequence
< OUString
> aDriverOrder
;
328 if ( 0 == lcl_getDriverPrecedence( m_xContext
, aDriverOrder
) )
332 // aDriverOrder now is the list of driver implementation names in the order they should be used
334 if ( m_aEventLogger
.isLoggable( LogLevel::CONFIG
) )
336 sal_Int32 nOrderedCount
= aDriverOrder
.getLength();
337 for ( sal_Int32 i
=0; i
<nOrderedCount
; ++i
)
338 m_aEventLogger
.log( LogLevel::CONFIG
,
339 "configuration's driver order: driver $1$ of $2$: $3$",
340 static_cast<sal_Int32
>(i
+ 1), nOrderedCount
, aDriverOrder
[i
]
344 // sort our bootstrapped drivers
345 std::sort( m_aDriversBS
.begin(), m_aDriversBS
.end(), CompareDriverAccessByName() );
347 // the first driver for which there is no preference
348 DriverAccessArray::iterator aNoPrefDriversStart
= m_aDriversBS
.begin();
349 // at the moment this is the first of all drivers we know
351 // loop through the names in the precedence order
352 for ( const OUString
& rDriverOrder
: std::as_const(aDriverOrder
) )
354 if (aNoPrefDriversStart
== m_aDriversBS
.end())
357 DriverAccess driver_order
;
358 driver_order
.sImplementationName
= rDriverOrder
;
360 // look for the impl name in the DriverAccess array
361 std::pair
< DriverAccessArray::iterator
, DriverAccessArray::iterator
> aPos
=
362 std::equal_range( aNoPrefDriversStart
, m_aDriversBS
.end(), driver_order
, CompareDriverAccessByName() );
364 if ( aPos
.first
!= aPos
.second
)
365 { // we have a DriverAccess with this impl name
367 OSL_ENSURE( std::distance( aPos
.first
, aPos
.second
) == 1,
368 "OSDBCDriverManager::initializeDriverPrecedence: more than one driver with this impl name? How this?" );
369 // move the DriverAccess pointed to by aPos.first to the position pointed to by aNoPrefDriversStart
371 if ( aPos
.first
!= aNoPrefDriversStart
)
372 { // if this does not hold, the DriverAccess already has the correct position
374 // rotate the range [aNoPrefDriversStart, aPos.second) right 1 element
375 std::rotate( aNoPrefDriversStart
, aPos
.second
- 1, aPos
.second
);
378 // next round we start searching and pos right
379 ++aNoPrefDriversStart
;
385 TOOLS_WARN_EXCEPTION( "connectivity.hsqldb", "OSDBCDriverManager::initializeDriverPrecedence: caught an exception while sorting the drivers!");
391 Reference
< XConnection
> SAL_CALL
OSDBCDriverManager::getConnection( const OUString
& _rURL
)
393 MutexGuard
aGuard(m_aMutex
);
395 m_aEventLogger
.log( LogLevel::INFO
,
396 "connection requested for URL $1$",
400 Reference
< XConnection
> xConnection
;
401 Reference
< XDriver
> xDriver
= implGetDriverForURL(_rURL
);
404 // TODO : handle the login timeout
405 xConnection
= xDriver
->connect(_rURL
, Sequence
< PropertyValue
>());
406 // may throw an exception
407 m_aEventLogger
.log( LogLevel::INFO
,
408 "connection retrieved for URL $1$",
417 Reference
< XConnection
> SAL_CALL
OSDBCDriverManager::getConnectionWithInfo( const OUString
& _rURL
, const Sequence
< PropertyValue
>& _rInfo
)
419 MutexGuard
aGuard(m_aMutex
);
421 m_aEventLogger
.log( LogLevel::INFO
,
422 "connection with info requested for URL $1$",
426 Reference
< XConnection
> xConnection
;
427 Reference
< XDriver
> xDriver
= implGetDriverForURL(_rURL
);
430 // TODO : handle the login timeout
431 xConnection
= xDriver
->connect(_rURL
, _rInfo
);
432 // may throw an exception
433 m_aEventLogger
.log( LogLevel::INFO
,
434 "connection with info retrieved for URL $1$",
443 void SAL_CALL
OSDBCDriverManager::setLoginTimeout( sal_Int32 seconds
)
445 MutexGuard
aGuard(m_aMutex
);
446 m_nLoginTimeout
= seconds
;
450 sal_Int32 SAL_CALL
OSDBCDriverManager::getLoginTimeout( )
452 MutexGuard
aGuard(m_aMutex
);
453 return m_nLoginTimeout
;
457 Reference
< XEnumeration
> SAL_CALL
OSDBCDriverManager::createEnumeration( )
459 MutexGuard
aGuard(m_aMutex
);
461 ODriverEnumeration::DriverArray aDrivers
;
463 // ensure that all our bootstrapped drivers are instantiated
464 std::for_each( m_aDriversBS
.begin(), m_aDriversBS
.end(), EnsureDriver( m_xContext
) );
466 // copy the bootstrapped drivers
468 m_aDriversBS
.begin(), // "copy from" start
469 m_aDriversBS
.end(), // "copy from" end
470 std::back_inserter( aDrivers
), // insert into
471 ExtractDriverFromAccess() // transformation to apply (extract a driver from a driver access)
474 // append the runtime drivers
476 m_aDriversRT
.begin(), // "copy from" start
477 m_aDriversRT
.end(), // "copy from" end
478 std::back_inserter( aDrivers
), // insert into
479 ExtractDriverFromCollectionElement() // transformation to apply (extract a driver from a driver access)
482 return new ODriverEnumeration( std::move(aDrivers
) );
486 css::uno::Type SAL_CALL
OSDBCDriverManager::getElementType( )
488 return cppu::UnoType
<XDriver
>::get();
492 sal_Bool SAL_CALL
OSDBCDriverManager::hasElements( )
494 MutexGuard
aGuard(m_aMutex
);
495 return !(m_aDriversBS
.empty() && m_aDriversRT
.empty());
499 OUString SAL_CALL
OSDBCDriverManager::getImplementationName( )
501 return "com.sun.star.comp.sdbc.OSDBCDriverManager";
504 sal_Bool SAL_CALL
OSDBCDriverManager::supportsService( const OUString
& _rServiceName
)
506 return cppu::supportsService(this, _rServiceName
);
510 Sequence
< OUString
> SAL_CALL
OSDBCDriverManager::getSupportedServiceNames( )
512 return { "com.sun.star.sdbc.DriverManager" };
516 Reference
< XInterface
> SAL_CALL
OSDBCDriverManager::getRegisteredObject( const OUString
& _rName
)
518 MutexGuard
aGuard(m_aMutex
);
519 DriverCollection::const_iterator aSearch
= m_aDriversRT
.find(_rName
);
520 if (aSearch
== m_aDriversRT
.end())
521 throwNoSuchElementException();
523 return aSearch
->second
;
527 void SAL_CALL
OSDBCDriverManager::registerObject( const OUString
& _rName
, const Reference
< XInterface
>& _rxObject
)
529 MutexGuard
aGuard(m_aMutex
);
531 m_aEventLogger
.log( LogLevel::INFO
,
532 "attempt to register new driver for name $1$",
536 DriverCollection::const_iterator aSearch
= m_aDriversRT
.find(_rName
);
537 if (aSearch
!= m_aDriversRT
.end())
538 throw ElementExistException();
539 Reference
< XDriver
> xNewDriver(_rxObject
, UNO_QUERY
);
540 if (!xNewDriver
.is())
541 throw IllegalArgumentException();
543 m_aDriversRT
.emplace(_rName
, xNewDriver
);
545 m_aEventLogger
.log( LogLevel::INFO
,
546 "new driver registered for name $1$",
552 void SAL_CALL
OSDBCDriverManager::revokeObject( const OUString
& _rName
)
554 MutexGuard
aGuard(m_aMutex
);
556 m_aEventLogger
.log( LogLevel::INFO
,
557 "attempt to revoke driver for name $1$",
561 DriverCollection::iterator aSearch
= m_aDriversRT
.find(_rName
);
562 if (aSearch
== m_aDriversRT
.end())
563 throwNoSuchElementException();
565 m_aDriversRT
.erase(aSearch
); // we already have the iterator so we could use it
567 m_aEventLogger
.log( LogLevel::INFO
,
568 "driver revoked for name $1$",
574 Reference
< XDriver
> SAL_CALL
OSDBCDriverManager::getDriverByURL( const OUString
& _rURL
)
576 m_aEventLogger
.log( LogLevel::INFO
,
577 "driver requested for URL $1$",
581 Reference
< XDriver
> xDriver( implGetDriverForURL( _rURL
) );
584 m_aEventLogger
.log( LogLevel::INFO
,
585 "driver obtained for URL $1$",
593 Reference
< XDriver
> OSDBCDriverManager::implGetDriverForURL(const OUString
& _rURL
)
595 Reference
< XDriver
> xReturn
;
598 const OUString sDriverFactoryName
= m_aDriverConfig
.getDriverFactoryName(_rURL
);
600 EqualDriverAccessToName
aEqual(sDriverFactoryName
);
601 DriverAccessArray::const_iterator aFind
= std::find_if(m_aDriversBS
.begin(),m_aDriversBS
.end(),aEqual
);
602 if ( aFind
== m_aDriversBS
.end() )
604 // search all bootstrapped drivers
605 aFind
= std::find_if(
606 m_aDriversBS
.begin(), // begin of search range
607 m_aDriversBS
.end(), // end of search range
608 [&_rURL
, this] (const DriverAccessArray::value_type
& driverAccess
) {
609 // extract the driver from the access, then ask the resulting driver for acceptance
610 #if defined __GNUC__ && !defined __clang__ && __GNUC__ == 13
611 #pragma GCC diagnostic push
612 #pragma GCC diagnostic ignored "-Wdangling-reference"
614 const DriverAccess
& ensuredAccess
= EnsureDriver(m_xContext
)(driverAccess
);
615 #if defined __GNUC__ && !defined __clang__ && __GNUC__ == 13
616 #pragma GCC diagnostic pop
618 const Reference
<XDriver
> driver
= ExtractDriverFromAccess()(ensuredAccess
);
619 return AcceptsURL(_rURL
, driver
);
621 } // if ( m_aDriversBS.find(sDriverFactoryName ) == m_aDriversBS.end() )
624 EnsureDriver
aEnsure( m_xContext
);
629 if ( m_aDriversBS
.end() != aFind
&& aFind
->xDriver
.is() && aFind
->xDriver
->acceptsURL(_rURL
) )
630 xReturn
= aFind
->xDriver
;
635 // no -> search the runtime drivers
636 DriverCollection::const_iterator aPos
= std::find_if(
637 m_aDriversRT
.begin(), // begin of search range
638 m_aDriversRT
.end(), // end of search range
639 [&_rURL
] (const DriverCollection::value_type
& element
) {
640 // extract the driver from the collection element, then ask the resulting driver for acceptance
641 const Reference
<XDriver
> driver
= ExtractDriverFromCollectionElement()(element
);
642 return AcceptsURL(_rURL
, driver
);
645 if ( m_aDriversRT
.end() != aPos
)
646 xReturn
= aPos
->second
;
652 } // namespace drivermanager
654 extern "C" SAL_DLLPUBLIC_EXPORT
css::uno::XInterface
*
655 connectivity_OSDBCDriverManager_get_implementation(
656 css::uno::XComponentContext
* context
, css::uno::Sequence
<css::uno::Any
> const&)
658 return cppu::acquire(new drivermanager::OSDBCDriverManager(context
));
662 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */