tdf#130857 qt weld: Support mail merge "Server Auth" dialog
[LibreOffice.git] / connectivity / source / manager / mdrivermanager.cxx
blob3d9754867bf7d13adb392ec054b71c9ee1e96bbb
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
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>
35 #include <officecfg/Office/DataAccess.hxx>
37 #include <algorithm>
38 #include <iterator>
39 #include <utility>
40 #include <vector>
42 namespace drivermanager
45 using namespace ::com::sun::star::uno;
46 using namespace ::com::sun::star::lang;
47 using namespace ::com::sun::star::sdbc;
48 using namespace ::com::sun::star::beans;
49 using namespace ::com::sun::star::container;
50 using namespace ::com::sun::star::logging;
51 using namespace ::osl;
53 constexpr OUStringLiteral SERVICE_SDBC_DRIVER = u"com.sun.star.sdbc.Driver";
55 class ODriverEnumeration : public ::cppu::WeakImplHelper< XEnumeration >
57 friend class OSDBCDriverManager;
59 typedef std::vector< Reference< XDriver > > DriverArray;
60 DriverArray m_aDrivers;
61 DriverArray::const_iterator m_aPos;
62 // order matters!
64 protected:
65 virtual ~ODriverEnumeration() override;
66 public:
67 explicit ODriverEnumeration(DriverArray&& _rDriverSequence);
69 // XEnumeration
70 virtual sal_Bool SAL_CALL hasMoreElements( ) override;
71 virtual Any SAL_CALL nextElement( ) override;
75 ODriverEnumeration::ODriverEnumeration(DriverArray&& _rDriverSequence)
76 :m_aDrivers( std::move(_rDriverSequence) )
77 ,m_aPos( m_aDrivers.begin() )
82 ODriverEnumeration::~ODriverEnumeration()
87 sal_Bool SAL_CALL ODriverEnumeration::hasMoreElements( )
89 return m_aPos != m_aDrivers.end();
93 Any SAL_CALL ODriverEnumeration::nextElement( )
95 if ( !hasMoreElements() )
96 throw NoSuchElementException();
98 return Any( *m_aPos++ );
101 namespace
103 /// an STL functor which ensures that a SdbcDriver described by a DriverAccess is loaded
104 struct EnsureDriver
106 explicit EnsureDriver( const Reference< XComponentContext > &rxContext )
107 : mxContext( rxContext ) {}
109 const DriverAccess& operator()( const DriverAccess& _rDescriptor ) const
111 // we did not load this driver, yet
112 if (_rDescriptor.xDriver.is())
113 return _rDescriptor;
115 // we have a factory for it
116 if (_rDescriptor.xComponentFactory.is())
118 DriverAccess& rDesc = const_cast<DriverAccess&>(_rDescriptor);
121 //load driver
122 rDesc.xDriver.set(
123 rDesc.xComponentFactory->createInstanceWithContext(mxContext), css::uno::UNO_QUERY);
125 catch (const Exception&)
127 //failure, abandon driver
128 rDesc.xComponentFactory.clear();
131 return _rDescriptor;
134 private:
135 Reference< XComponentContext > mxContext;
138 /// an STL functor which extracts a SdbcDriver from a DriverAccess
139 struct ExtractDriverFromAccess
141 const Reference<XDriver>& operator()( const DriverAccess& _rAccess ) const
143 return _rAccess.xDriver;
147 struct ExtractDriverFromCollectionElement
149 const Reference<XDriver>& operator()( const DriverCollection::value_type& _rElement ) const
151 return _rElement.second;
155 // predicate for checking whether or not a driver accepts a given URL
156 bool AcceptsURL( const OUString& _rURL, const Reference<XDriver>& _rDriver )
158 // ask the driver
159 return _rDriver.is() && _rDriver->acceptsURL( _rURL );
162 /// an STL algorithm compatible predicate comparing two DriverAccess instances by their implementation names
163 struct CompareDriverAccessByName
166 bool operator()( const DriverAccess& lhs, const DriverAccess& rhs )
168 return lhs.sImplementationName < rhs.sImplementationName;
172 /// and an STL algorithm compatible predicate comparing the impl name of a DriverAccess to a string
173 struct EqualDriverAccessToName
175 OUString m_sImplName;
176 explicit EqualDriverAccessToName(OUString _sImplName) : m_sImplName(std::move(_sImplName)){}
178 bool operator()( const DriverAccess& lhs)
180 return lhs.sImplementationName == m_sImplName;
185 OSDBCDriverManager::OSDBCDriverManager( const Reference< XComponentContext >& _rxContext )
186 :OSDBCDriverManager_Base(m_aMutex)
187 ,m_xContext( _rxContext )
188 ,m_aEventLogger( _rxContext, "org.openoffice.logging.sdbc.DriverManager" )
189 ,m_aDriverConfig(m_xContext)
190 ,m_nLoginTimeout(0)
192 // bootstrap all objects supporting the .sdb.Driver service
193 bootstrapDrivers();
195 // initialize the drivers order
196 initializeDriverPrecedence();
200 OSDBCDriverManager::~OSDBCDriverManager()
204 void OSDBCDriverManager::bootstrapDrivers()
206 Reference< XContentEnumerationAccess > xEnumAccess( m_xContext->getServiceManager(), UNO_QUERY );
207 Reference< XEnumeration > xEnumDrivers;
208 if (xEnumAccess.is())
209 xEnumDrivers = xEnumAccess->createContentEnumeration(SERVICE_SDBC_DRIVER);
211 OSL_ENSURE( xEnumDrivers.is(), "OSDBCDriverManager::bootstrapDrivers: no enumeration for the drivers available!" );
212 if (!xEnumDrivers.is())
213 return;
215 Reference< XSingleComponentFactory > xFactory;
216 Reference< XServiceInfo > xSI;
217 while (xEnumDrivers->hasMoreElements())
219 xFactory.set(xEnumDrivers->nextElement(), css::uno::UNO_QUERY);
220 OSL_ENSURE( xFactory.is(), "OSDBCDriverManager::bootstrapDrivers: no factory extracted" );
222 if ( xFactory.is() )
224 // we got a factory for the driver
225 DriverAccess aDriverDescriptor;
226 bool bValidDescriptor = false;
228 // can it tell us something about the implementation name?
229 xSI.set(xFactory, css::uno::UNO_QUERY);
230 if ( xSI.is() )
231 { // yes -> no need to load the driver immediately (load it later when needed)
232 aDriverDescriptor.sImplementationName = xSI->getImplementationName();
233 aDriverDescriptor.xComponentFactory = xFactory;
234 bValidDescriptor = true;
236 m_aEventLogger.log( LogLevel::CONFIG,
237 "found SDBC driver $1$, no need to load it",
238 aDriverDescriptor.sImplementationName
241 else
243 // no -> create the driver
244 Reference< XDriver > xDriver( xFactory->createInstanceWithContext( m_xContext ), UNO_QUERY );
245 OSL_ENSURE( xDriver.is(), "OSDBCDriverManager::bootstrapDrivers: a driver which is no driver?!" );
247 if ( xDriver.is() )
249 aDriverDescriptor.xDriver = xDriver;
250 // and obtain its implementation name
251 xSI.set(xDriver, css::uno::UNO_QUERY);
252 OSL_ENSURE( xSI.is(), "OSDBCDriverManager::bootstrapDrivers: a driver without service info?" );
253 if ( xSI.is() )
255 aDriverDescriptor.sImplementationName = xSI->getImplementationName();
256 bValidDescriptor = true;
258 m_aEventLogger.log( LogLevel::CONFIG,
259 "found SDBC driver $1$, needed to load it",
260 aDriverDescriptor.sImplementationName
266 if ( bValidDescriptor )
268 m_aDriversBS.push_back( aDriverDescriptor );
275 void OSDBCDriverManager::initializeDriverPrecedence()
277 #if !ENABLE_FUZZERS
278 if ( m_aDriversBS.empty() )
279 // nothing to do
280 return;
284 // get the precedence of the drivers from the configuration
285 Sequence< OUString > aDriverOrder = officecfg::Office::DataAccess::DriverManager::DriverPrecedence::get();
286 if ( 0 == aDriverOrder.getLength() )
287 // nothing to do
288 return;
290 // aDriverOrder now is the list of driver implementation names in the order they should be used
292 if ( m_aEventLogger.isLoggable( LogLevel::CONFIG ) )
294 sal_Int32 nOrderedCount = aDriverOrder.getLength();
295 for ( sal_Int32 i=0; i<nOrderedCount; ++i )
296 m_aEventLogger.log( LogLevel::CONFIG,
297 "configuration's driver order: driver $1$ of $2$: $3$",
298 static_cast<sal_Int32>(i + 1), nOrderedCount, aDriverOrder[i]
302 // sort our bootstrapped drivers
303 std::sort( m_aDriversBS.begin(), m_aDriversBS.end(), CompareDriverAccessByName() );
305 // the first driver for which there is no preference
306 DriverAccessArray::iterator aNoPrefDriversStart = m_aDriversBS.begin();
307 // at the moment this is the first of all drivers we know
309 // loop through the names in the precedence order
310 for (const OUString& rDriverOrder : aDriverOrder)
312 if (aNoPrefDriversStart == m_aDriversBS.end())
313 break;
315 DriverAccess driver_order;
316 driver_order.sImplementationName = rDriverOrder;
318 // look for the impl name in the DriverAccess array
319 std::pair< DriverAccessArray::iterator, DriverAccessArray::iterator > aPos =
320 std::equal_range( aNoPrefDriversStart, m_aDriversBS.end(), driver_order, CompareDriverAccessByName() );
322 if ( aPos.first != aPos.second )
323 { // we have a DriverAccess with this impl name
325 OSL_ENSURE( std::distance( aPos.first, aPos.second ) == 1,
326 "OSDBCDriverManager::initializeDriverPrecedence: more than one driver with this impl name? How this?" );
327 // move the DriverAccess pointed to by aPos.first to the position pointed to by aNoPrefDriversStart
329 if ( aPos.first != aNoPrefDriversStart )
330 { // if this does not hold, the DriverAccess already has the correct position
332 // rotate the range [aNoPrefDriversStart, aPos.second) right 1 element
333 std::rotate( aNoPrefDriversStart, aPos.second - 1, aPos.second );
336 // next round we start searching and pos right
337 ++aNoPrefDriversStart;
341 catch (Exception&)
343 TOOLS_WARN_EXCEPTION( "connectivity.hsqldb", "OSDBCDriverManager::initializeDriverPrecedence: caught an exception while sorting the drivers!");
345 #endif
349 Reference< XConnection > SAL_CALL OSDBCDriverManager::getConnection( const OUString& _rURL )
351 MutexGuard aGuard(m_aMutex);
353 m_aEventLogger.log( LogLevel::INFO,
354 "connection requested for URL $1$",
355 _rURL
358 Reference< XConnection > xConnection;
359 Reference< XDriver > xDriver = implGetDriverForURL(_rURL);
360 if (xDriver.is())
362 // TODO : handle the login timeout
363 xConnection = xDriver->connect(_rURL, Sequence< PropertyValue >());
364 // may throw an exception
365 m_aEventLogger.log( LogLevel::INFO,
366 "connection retrieved for URL $1$",
367 _rURL
371 return xConnection;
375 Reference< XConnection > SAL_CALL OSDBCDriverManager::getConnectionWithInfo( const OUString& _rURL, const Sequence< PropertyValue >& _rInfo )
377 MutexGuard aGuard(m_aMutex);
379 m_aEventLogger.log( LogLevel::INFO,
380 "connection with info requested for URL $1$",
381 _rURL
384 Reference< XConnection > xConnection;
385 Reference< XDriver > xDriver = implGetDriverForURL(_rURL);
386 if (xDriver.is())
388 // TODO : handle the login timeout
389 xConnection = xDriver->connect(_rURL, _rInfo);
390 // may throw an exception
391 m_aEventLogger.log( LogLevel::INFO,
392 "connection with info retrieved for URL $1$",
393 _rURL
397 return xConnection;
401 void SAL_CALL OSDBCDriverManager::setLoginTimeout( sal_Int32 seconds )
403 MutexGuard aGuard(m_aMutex);
404 m_nLoginTimeout = seconds;
408 sal_Int32 SAL_CALL OSDBCDriverManager::getLoginTimeout( )
410 MutexGuard aGuard(m_aMutex);
411 return m_nLoginTimeout;
415 Reference< XEnumeration > SAL_CALL OSDBCDriverManager::createEnumeration( )
417 MutexGuard aGuard(m_aMutex);
419 ODriverEnumeration::DriverArray aDrivers;
421 // ensure that all our bootstrapped drivers are instantiated
422 std::for_each( m_aDriversBS.begin(), m_aDriversBS.end(), EnsureDriver( m_xContext ) );
424 // copy the bootstrapped drivers
425 std::transform(
426 m_aDriversBS.begin(), // "copy from" start
427 m_aDriversBS.end(), // "copy from" end
428 std::back_inserter( aDrivers ), // insert into
429 ExtractDriverFromAccess() // transformation to apply (extract a driver from a driver access)
432 // append the runtime drivers
433 std::transform(
434 m_aDriversRT.begin(), // "copy from" start
435 m_aDriversRT.end(), // "copy from" end
436 std::back_inserter( aDrivers ), // insert into
437 ExtractDriverFromCollectionElement() // transformation to apply (extract a driver from a driver access)
440 return new ODriverEnumeration( std::move(aDrivers) );
444 css::uno::Type SAL_CALL OSDBCDriverManager::getElementType( )
446 return cppu::UnoType<XDriver>::get();
450 sal_Bool SAL_CALL OSDBCDriverManager::hasElements( )
452 MutexGuard aGuard(m_aMutex);
453 return !(m_aDriversBS.empty() && m_aDriversRT.empty());
457 OUString SAL_CALL OSDBCDriverManager::getImplementationName( )
459 return u"com.sun.star.comp.sdbc.OSDBCDriverManager"_ustr;
462 sal_Bool SAL_CALL OSDBCDriverManager::supportsService( const OUString& _rServiceName )
464 return cppu::supportsService(this, _rServiceName);
468 Sequence< OUString > SAL_CALL OSDBCDriverManager::getSupportedServiceNames( )
470 return { u"com.sun.star.sdbc.DriverManager"_ustr };
474 Reference< XInterface > SAL_CALL OSDBCDriverManager::getRegisteredObject( const OUString& _rName )
476 MutexGuard aGuard(m_aMutex);
477 DriverCollection::const_iterator aSearch = m_aDriversRT.find(_rName);
478 if (aSearch == m_aDriversRT.end())
479 throw NoSuchElementException();
481 return aSearch->second;
485 void SAL_CALL OSDBCDriverManager::registerObject( const OUString& _rName, const Reference< XInterface >& _rxObject )
487 MutexGuard aGuard(m_aMutex);
489 m_aEventLogger.log( LogLevel::INFO,
490 "attempt to register new driver for name $1$",
491 _rName
494 DriverCollection::const_iterator aSearch = m_aDriversRT.find(_rName);
495 if (aSearch != m_aDriversRT.end())
496 throw ElementExistException();
497 Reference< XDriver > xNewDriver(_rxObject, UNO_QUERY);
498 if (!xNewDriver.is())
499 throw IllegalArgumentException();
501 m_aDriversRT.emplace(_rName, xNewDriver);
503 m_aEventLogger.log( LogLevel::INFO,
504 "new driver registered for name $1$",
505 _rName
510 void SAL_CALL OSDBCDriverManager::revokeObject( const OUString& _rName )
512 MutexGuard aGuard(m_aMutex);
514 m_aEventLogger.log( LogLevel::INFO,
515 "attempt to revoke driver for name $1$",
516 _rName
519 DriverCollection::iterator aSearch = m_aDriversRT.find(_rName);
520 if (aSearch == m_aDriversRT.end())
521 throw NoSuchElementException();
523 m_aDriversRT.erase(aSearch); // we already have the iterator so we could use it
525 m_aEventLogger.log( LogLevel::INFO,
526 "driver revoked for name $1$",
527 _rName
532 Reference< XDriver > SAL_CALL OSDBCDriverManager::getDriverByURL( const OUString& _rURL )
534 m_aEventLogger.log( LogLevel::INFO,
535 "driver requested for URL $1$",
536 _rURL
539 Reference< XDriver > xDriver( implGetDriverForURL( _rURL ) );
541 if ( xDriver.is() )
542 m_aEventLogger.log( LogLevel::INFO,
543 "driver obtained for URL $1$",
544 _rURL
547 return xDriver;
551 Reference< XDriver > OSDBCDriverManager::implGetDriverForURL(const OUString& _rURL)
553 Reference< XDriver > xReturn;
556 const OUString sDriverFactoryName = m_aDriverConfig.getDriverFactoryName(_rURL);
558 DriverAccessArray::const_iterator aFind = std::find_if(m_aDriversBS.begin(), m_aDriversBS.end(),
559 EqualDriverAccessToName(sDriverFactoryName));
560 if ( aFind == m_aDriversBS.end() )
562 // search all bootstrapped drivers
563 aFind = std::find_if(
564 m_aDriversBS.begin(), // begin of search range
565 m_aDriversBS.end(), // end of search range
566 [&_rURL, this] (const DriverAccessArray::value_type& driverAccess) {
567 // extract the driver from the access, then ask the resulting driver for acceptance
568 #if defined __GNUC__ && !defined __clang__ && __GNUC__ >= 13 && __GNUC__ <= 15
569 #pragma GCC diagnostic push
570 #pragma GCC diagnostic ignored "-Wdangling-reference"
571 #endif
572 const DriverAccess& ensuredAccess = EnsureDriver(m_xContext)(driverAccess);
573 #if defined __GNUC__ && !defined __clang__ && __GNUC__ >= 13 && __GNUC__ <= 15
574 #pragma GCC diagnostic pop
575 #endif
576 const Reference<XDriver> driver = ExtractDriverFromAccess()(ensuredAccess);
577 return AcceptsURL(_rURL, driver);
579 } // if ( m_aDriversBS.find(sDriverFactoryName ) == m_aDriversBS.end() )
580 else
582 EnsureDriver aEnsure( m_xContext );
583 aEnsure(*aFind);
586 // found something?
587 if ( m_aDriversBS.end() != aFind && aFind->xDriver.is() && aFind->xDriver->acceptsURL(_rURL) )
588 xReturn = aFind->xDriver;
591 if ( !xReturn.is() )
593 // no -> search the runtime drivers
594 DriverCollection::const_iterator aPos = std::find_if(
595 m_aDriversRT.begin(), // begin of search range
596 m_aDriversRT.end(), // end of search range
597 [&_rURL] (const DriverCollection::value_type& element) {
598 // extract the driver from the collection element, then ask the resulting driver for acceptance
599 const Reference<XDriver> driver = ExtractDriverFromCollectionElement()(element);
600 return AcceptsURL(_rURL, driver);
603 if ( m_aDriversRT.end() != aPos )
604 xReturn = aPos->second;
607 return xReturn;
610 } // namespace drivermanager
612 extern "C" SAL_DLLPUBLIC_EXPORT css::uno::XInterface*
613 connectivity_OSDBCDriverManager_get_implementation(
614 css::uno::XComponentContext* context , css::uno::Sequence<css::uno::Any> const&)
616 return cppu::acquire(new drivermanager::OSDBCDriverManager(context));
620 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */