merge the formfield patch from ooo-build
[ooovba.git] / xmlsecurity / source / xmlsec / nss / seinitializer_nssimpl.cxx
blob1966d945e83ec48dc0accfd66aa3f094bb1bbca7
1 /*************************************************************************
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * Copyright 2008 by Sun Microsystems, Inc.
7 * OpenOffice.org - a multi-platform office productivity suite
9 * $RCSfile: seinitializer_nssimpl.cxx,v $
10 * $Revision: 1.22 $
12 * This file is part of OpenOffice.org.
14 * OpenOffice.org is free software: you can redistribute it and/or modify
15 * it under the terms of the GNU Lesser General Public License version 3
16 * only, as published by the Free Software Foundation.
18 * OpenOffice.org is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU Lesser General Public License version 3 for more details
22 * (a copy is included in the LICENSE file that accompanied this code).
24 * You should have received a copy of the GNU Lesser General Public License
25 * version 3 along with OpenOffice.org. If not, see
26 * <http://www.openoffice.org/license.html>
27 * for a copy of the LGPLv3 License.
29 ************************************************************************/
31 // MARKER(update_precomp.py): autogen include statement, do not remove
32 #include "precompiled_xmlsecurity.hxx"
35 * Turn off DEBUG Assertions
37 #ifdef _DEBUG
38 #define _DEBUG_WAS_DEFINED _DEBUG
39 #undef _DEBUG
40 #else
41 #undef _DEBUG_WAS_DEFINED
42 #endif
45 * and turn off the additional virtual methods which are part of some interfaces when compiled
46 * with debug
48 #ifdef DEBUG
49 #define DEBUG_WAS_DEFINED DEBUG
50 #undef DEBUG
51 #else
52 #undef DEBUG_WAS_DEFINED
53 #endif
56 #include <sal/types.h>
57 #include "rtl/instance.hxx"
58 #include "rtl/bootstrap.hxx"
59 #include "rtl/string.hxx"
60 #include "rtl/strbuf.hxx"
61 #include "osl/file.hxx"
62 #include "osl/thread.h"
63 #include <tools/debug.hxx>
64 #include <rtl/logfile.hxx>
66 #include "seinitializer_nssimpl.hxx"
68 #include "securityenvironment_nssimpl.hxx"
69 #include <com/sun/star/mozilla/XMozillaBootstrap.hpp>
71 #include "nspr.h"
72 #include "cert.h"
73 #include "nss.h"
74 #include "secmod.h"
75 #include "nssckbi.h"
78 namespace cssu = com::sun::star::uno;
79 namespace cssl = com::sun::star::lang;
80 namespace cssxc = com::sun::star::xml::crypto;
82 using namespace com::sun::star;
83 using ::rtl::OUString;
84 using ::rtl::OString;
86 #define SERVICE_NAME "com.sun.star.xml.crypto.SEInitializer"
87 #define IMPLEMENTATION_NAME "com.sun.star.xml.security.bridge.xmlsec.SEInitializer_NssImpl"
88 #define SECURITY_ENVIRONMENT "com.sun.star.xml.crypto.SecurityEnvironment"
89 #define SECURITY_CONTEXT "com.sun.star.xml.crypto.XMLSecurityContext"
92 #define ROOT_CERTS "Root Certs for OpenOffice.org"
95 extern "C" void nsscrypto_finalize();
98 namespace
101 bool nsscrypto_initialize( const char * sProfile, bool & out_nss_init);
103 struct InitNSSInitialize
105 //path to the database folder
106 const OString m_sProfile;
107 InitNSSInitialize(const OString & sProfile): m_sProfile(sProfile) {};
108 bool * operator()()
110 static bool bInitialized = false;
111 bool bNSSInit = false;
112 bInitialized = nsscrypto_initialize(m_sProfile.getStr(), bNSSInit);
113 if (bNSSInit)
114 atexit(nsscrypto_finalize );
115 return & bInitialized;
120 bool * initNSS(const OString & sProfile)
122 return rtl_Instance< bool, InitNSSInitialize,
123 ::osl::MutexGuard, ::osl::GetGlobalMutex >::create(
124 InitNSSInitialize(sProfile), ::osl::GetGlobalMutex());
127 void deleteRootsModule()
129 SECMODModule *RootsModule = 0;
130 SECMODModuleList *list = SECMOD_GetDefaultModuleList();
131 SECMODListLock *lock = SECMOD_GetDefaultModuleListLock();
132 SECMOD_GetReadLock(lock);
134 while (!RootsModule && list)
136 SECMODModule *module = list->module;
138 for (int i=0; i < module->slotCount; i++)
140 PK11SlotInfo *slot = module->slots[i];
141 if (PK11_IsPresent(slot))
143 if (PK11_HasRootCerts(slot))
145 OSL_TRACE("[xmlsecurity] The root certifificates module \"%s"
146 "\" is already loaded: \n%s",
147 module->commonName, module->dllName);
149 RootsModule = SECMOD_ReferenceModule(module);
150 break;
154 list = list->next;
156 SECMOD_ReleaseReadLock(lock);
158 if (RootsModule)
160 PRInt32 modType;
161 if (SECSuccess == SECMOD_DeleteModule(RootsModule->commonName, &modType))
163 OSL_TRACE("[xmlsecurity] Deleted module \"%s\".", RootsModule->commonName);
165 else
167 OSL_TRACE("[xmlsecurity] Failed to delete \"%s\" : \n%s",
168 RootsModule->commonName, RootsModule->dllName);
170 SECMOD_DestroyModule(RootsModule);
171 RootsModule = 0;
175 //Older versions of Firefox (FF), for example FF2, and Thunderbird (TB) 2 write
176 //the roots certificate module (libnssckbi.so), which they use, into the
177 //profile. This module will then already be loaded during NSS_Init (and the
178 //other init functions). This fails in two cases. First, FF3 was used to create
179 //the profile, or possibly used that profile before, and second the profile was
180 //used on a different platform.
182 //Then one needs to add the roots module oneself. This should be done with
183 //SECMOD_LoadUserModule rather then SECMOD_AddNewModule. The latter would write
184 //the location of the roots module to the profile, which makes FF2 and TB2 use
185 //it instead of there own module.
187 //When using SYSTEM_MOZILLA then the libnss3.so lib is typically found in
188 ///usr/lib. This folder may, however, NOT contain the roots certificate
189 //module. That is, just providing the library name in SECMOD_LoadUserModule or
190 //SECMOD_AddNewModule will FAIL to load the mozilla unless the LD_LIBRARY_PATH
191 //contains an FF or TB installation.
192 //ATTENTION: DO NOT call this function directly instead use initNSS
193 //return true - whole initialization was successful
194 //param out_nss_init = true: at least the NSS initialization (NSS_InitReadWrite
195 //was successful and therefor NSS_Shutdown should be called when terminating.
196 bool nsscrypto_initialize( const char* token, bool & out_nss_init )
198 bool return_value = true;
200 OSL_TRACE("[xmlsecurity] Using profile: %s", token);
202 PR_Init( PR_USER_THREAD, PR_PRIORITY_NORMAL, 1 ) ;
204 if( NSS_InitReadWrite( token ) != SECSuccess )
206 char * error = NULL;
208 PR_GetErrorText(error);
209 if (error)
210 printf("%s",error);
211 return false ;
213 out_nss_init = true;
215 #if defined SYSTEM_MOZILLA
216 if (!SECMOD_HasRootCerts())
218 #endif
219 deleteRootsModule();
221 #if defined SYSTEM_MOZILLA
222 OUString rootModule(RTL_CONSTASCII_USTRINGPARAM("libnssckbi"SAL_DLLEXTENSION));
223 #else
224 OUString rootModule(RTL_CONSTASCII_USTRINGPARAM("${OOO_BASE_DIR}/program/libnssckbi"SAL_DLLEXTENSION));
225 #endif
226 ::rtl::Bootstrap::expandMacros(rootModule);
228 OUString rootModulePath;
229 if (::osl::File::E_None == ::osl::File::getSystemPathFromFileURL(rootModule, rootModulePath))
231 ::rtl::OString ospath = ::rtl::OUStringToOString(rootModulePath, osl_getThreadTextEncoding());
232 ::rtl::OStringBuffer pkcs11moduleSpec;
233 pkcs11moduleSpec.append("name=\"");
234 pkcs11moduleSpec.append(ROOT_CERTS);
235 pkcs11moduleSpec.append("\" library=\"");
236 pkcs11moduleSpec.append(ospath.getStr());
237 pkcs11moduleSpec.append("\"");
239 SECMODModule * RootsModule =
240 SECMOD_LoadUserModule(
241 const_cast<char*>(pkcs11moduleSpec.makeStringAndClear().getStr()),
242 0, // no parent
243 PR_FALSE); // do not recurse
245 if (RootsModule)
248 bool found = RootsModule->loaded;
250 SECMOD_DestroyModule(RootsModule);
251 RootsModule = 0;
252 if (found)
253 OSL_TRACE("[xmlsecurity] Added new root certificate module "
254 "\""ROOT_CERTS"\" contained in \n%s", ospath.getStr());
255 else
257 OSL_TRACE("[xmlsecurity] FAILED to load the new root certificate module "
258 "\""ROOT_CERTS"\" contained in \n%s", ospath.getStr());
259 return_value = false;
262 else
264 OSL_TRACE("[xmlsecurity] FAILED to add new root certifice module: "
265 "\""ROOT_CERTS"\" contained in \n%s", ospath.getStr());
266 return_value = false;
270 else
272 OSL_TRACE("[xmlsecurity] Adding new root certificate module failed.");
273 return_value = false;
275 #if SYSTEM_MOZILLA
277 #endif
279 return return_value;
283 // must be extern "C" because we pass the function pointer to atexit
284 extern "C" void nsscrypto_finalize()
286 SECMODModule *RootsModule = SECMOD_FindModule(ROOT_CERTS);
288 if (RootsModule)
291 if (SECSuccess == SECMOD_UnloadUserModule(RootsModule))
293 OSL_TRACE("[xmlsecurity] Unloaded module \""ROOT_CERTS"\".");
295 else
297 OSL_TRACE("[xmlsecurity] Failed unloadeding module \""ROOT_CERTS"\".");
299 SECMOD_DestroyModule(RootsModule);
301 else
303 OSL_TRACE("[xmlsecurity] Unloading module \""ROOT_CERTS
304 "\" failed because it was not found.");
306 PK11_LogoutAll();
307 NSS_Shutdown();
311 bool getMozillaCurrentProfile(
312 const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory > &rxMSF,
313 rtl::OUString& profilePath)
316 * first, try to get the profile from "MOZILLA_CERTIFICATE_FOLDER"
318 char * env = getenv("MOZILLA_CERTIFICATE_FOLDER");
319 if (env)
321 profilePath = rtl::OUString::createFromAscii( env );
322 RTL_LOGFILE_PRODUCT_TRACE1( "XMLSEC: Using env MOZILLA_CERTIFICATE_FOLDER: %s", rtl::OUStringToOString( profilePath, RTL_TEXTENCODING_ASCII_US ).getStr() );
323 return true;
325 else
327 RTL_LOGFILE_TRACE( "getMozillaCurrentProfile: Using MozillaBootstrap..." );
328 mozilla::MozillaProductType productTypes[4] = {
329 mozilla::MozillaProductType_Thunderbird,
330 mozilla::MozillaProductType_Mozilla,
331 mozilla::MozillaProductType_Firefox,
332 mozilla::MozillaProductType_Default };
333 int nProduct = 4;
335 uno::Reference<uno::XInterface> xInstance = rxMSF->createInstance(
336 ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.mozilla.MozillaBootstrap")) );
337 OSL_ENSURE( xInstance.is(), "failed to create instance" );
339 uno::Reference<mozilla::XMozillaBootstrap> xMozillaBootstrap
340 = uno::Reference<mozilla::XMozillaBootstrap>(xInstance,uno::UNO_QUERY);
341 OSL_ENSURE( xMozillaBootstrap.is(), "failed to create instance" );
343 if (xMozillaBootstrap.is())
345 for (int i=0; i<nProduct; i++)
347 ::rtl::OUString profile = xMozillaBootstrap->getDefaultProfile(productTypes[i]);
349 RTL_LOGFILE_TRACE2( "getMozillaCurrentProfile: getDefaultProfile [%i] returns %s", i, rtl::OUStringToOString( profile, RTL_TEXTENCODING_ASCII_US ).getStr() );
351 if (profile != NULL && profile.getLength()>0)
353 profilePath = xMozillaBootstrap->getProfilePath(productTypes[i],profile);
354 RTL_LOGFILE_PRODUCT_TRACE1( "XMLSEC: Using Mozilla Profile: %s", rtl::OUStringToOString( profilePath, RTL_TEXTENCODING_ASCII_US ).getStr() );
355 return true;
360 RTL_LOGFILE_PRODUCT_TRACE( "XMLSEC: No Mozilla Profile found!" );
361 return false;
365 } // namespace
367 SEInitializer_NssImpl::SEInitializer_NssImpl(
368 const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory > &rxMSF)
369 :mxMSF( rxMSF )
373 SEInitializer_NssImpl::~SEInitializer_NssImpl()
377 /* XSEInitializer */
378 cssu::Reference< cssxc::XXMLSecurityContext > SAL_CALL
379 SEInitializer_NssImpl::createSecurityContext(
380 const rtl::OUString& sCertDB )
381 throw (cssu::RuntimeException)
383 CERTCertDBHandle *pCertHandle = NULL ;
385 rtl::OString sCertDir;
386 if( sCertDB.getLength() )
388 sCertDir = rtl::OString(sCertDB, sCertDB.getLength(), RTL_TEXTENCODING_ASCII_US);
390 else
392 static rtl::OString* pDefaultCertDir = NULL;
393 if ( !pDefaultCertDir )
395 pDefaultCertDir = new rtl::OString;
396 rtl::OUString ouCertDir;
400 if ( getMozillaCurrentProfile(mxMSF, ouCertDir) )
401 *pDefaultCertDir = rtl::OString(ouCertDir, ouCertDir.getLength(), RTL_TEXTENCODING_ASCII_US);
403 sCertDir = *pDefaultCertDir;
407 if( !sCertDir.getLength() )
409 RTL_LOGFILE_TRACE( "XMLSEC: Error - No certificate directory!" );
410 // return NULL;
414 /* Initialize NSPR and NSS */
415 /* Replaced with new methods by AF. ----
416 //PR_Init( PR_SYSTEM_THREAD, PR_PRIORITY_NORMAL, 1 ) ;
417 PR_Init( PR_USER_THREAD, PR_PRIORITY_NORMAL, 1 ) ;
419 if (NSS_Init(sCertDir.getStr()) != SECSuccess )
421 PK11_LogoutAll();
422 return NULL;
424 ----*/
425 if( ! *initNSS( sCertDir.getStr() ) )
427 RTL_LOGFILE_TRACE( "XMLSEC: Error - nsscrypto_initialize() failed." );
428 if ( NSS_NoDB_Init(NULL) != SECSuccess )
430 RTL_LOGFILE_TRACE( "XMLSEC: NSS_NoDB_Init also failed, NSS Security not available!" );
431 return NULL;
433 else
435 RTL_LOGFILE_TRACE( "XMLSEC: NSS_NoDB_Init works, enough for verifying signatures..." );
439 pCertHandle = CERT_GetDefaultCertDB() ;
441 try
443 /* Build XML Security Context */
444 const rtl::OUString sSecyrutyContext ( RTL_CONSTASCII_USTRINGPARAM( SECURITY_CONTEXT ) );
445 cssu::Reference< cssxc::XXMLSecurityContext > xSecCtx( mxMSF->createInstance ( sSecyrutyContext ), cssu::UNO_QUERY );
446 if( !xSecCtx.is() )
447 return NULL;
449 const rtl::OUString sSecyrutyEnvironment ( RTL_CONSTASCII_USTRINGPARAM( SECURITY_ENVIRONMENT ) );
450 cssu::Reference< cssxc::XSecurityEnvironment > xSecEnv( mxMSF->createInstance ( sSecyrutyEnvironment ), cssu::UNO_QUERY );
451 cssu::Reference< cssl::XUnoTunnel > xEnvTunnel( xSecEnv , cssu::UNO_QUERY ) ;
452 if( !xEnvTunnel.is() )
453 return NULL;
454 SecurityEnvironment_NssImpl* pSecEnv = reinterpret_cast<SecurityEnvironment_NssImpl*>(
455 sal::static_int_cast<sal_uIntPtr>(
456 xEnvTunnel->getSomething(SecurityEnvironment_NssImpl::getUnoTunnelId() ))) ;
457 pSecEnv->setCertDb(pCertHandle);
459 sal_Int32 n = xSecCtx->addSecurityEnvironment(xSecEnv);
460 //originally the SecurityEnvironment with the internal slot was set as default
461 xSecCtx->setDefaultSecurityEnvironmentIndex( n );
462 return xSecCtx;
464 catch( cssu::Exception& )
466 //PK11_LogoutAll();
467 //NSS_Shutdown();
468 return NULL;
472 void SAL_CALL SEInitializer_NssImpl::freeSecurityContext( const cssu::Reference< cssxc::XXMLSecurityContext >& )
473 throw (cssu::RuntimeException)
476 * because the security context will free all its content when it
477 * is destructed, so here no free process for the security context
478 * is needed.
480 //PK11_LogoutAll();
481 //NSS_Shutdown();
484 rtl::OUString SEInitializer_NssImpl_getImplementationName ()
485 throw (cssu::RuntimeException)
488 return rtl::OUString ( RTL_CONSTASCII_USTRINGPARAM ( IMPLEMENTATION_NAME ) );
491 sal_Bool SAL_CALL SEInitializer_NssImpl_supportsService( const rtl::OUString& ServiceName )
492 throw (cssu::RuntimeException)
494 return ServiceName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM ( SERVICE_NAME ));
497 cssu::Sequence< rtl::OUString > SAL_CALL SEInitializer_NssImpl_getSupportedServiceNames( )
498 throw (cssu::RuntimeException)
500 cssu::Sequence < rtl::OUString > aRet(1);
501 rtl::OUString* pArray = aRet.getArray();
502 pArray[0] = rtl::OUString ( RTL_CONSTASCII_USTRINGPARAM ( SERVICE_NAME ) );
503 return aRet;
505 #undef SERVICE_NAME
507 cssu::Reference< cssu::XInterface > SAL_CALL SEInitializer_NssImpl_createInstance( const cssu::Reference< cssl::XMultiServiceFactory > & rSMgr)
508 throw( cssu::Exception )
510 return (cppu::OWeakObject*) new SEInitializer_NssImpl(rSMgr);
513 /* XServiceInfo */
514 rtl::OUString SAL_CALL SEInitializer_NssImpl::getImplementationName( )
515 throw (cssu::RuntimeException)
517 return SEInitializer_NssImpl_getImplementationName();
519 sal_Bool SAL_CALL SEInitializer_NssImpl::supportsService( const rtl::OUString& rServiceName )
520 throw (cssu::RuntimeException)
522 return SEInitializer_NssImpl_supportsService( rServiceName );
524 cssu::Sequence< rtl::OUString > SAL_CALL SEInitializer_NssImpl::getSupportedServiceNames( )
525 throw (cssu::RuntimeException)
527 return SEInitializer_NssImpl_getSupportedServiceNames();