vcl: Create HFNT on WinFontFace when needed
[LibreOffice.git] / xmlsecurity / source / dialogs / certificatechooser.cxx
blob3ac503521e727f826949b91293a97548db699074
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_gpgme.h>
21 #include <certificatechooser.hxx>
22 #include <certificateviewer.hxx>
23 #include <com/sun/star/xml/crypto/XSecurityEnvironment.hpp>
24 #include <com/sun/star/xml/crypto/XXMLSecurityContext.hpp>
25 #include <comphelper/sequence.hxx>
26 #include <comphelper/xmlsechelper.hxx>
28 #include <com/sun/star/security/NoPasswordException.hpp>
29 #include <com/sun/star/security/CertificateCharacters.hpp>
31 #include <o3tl/safeint.hxx>
32 #include <unotools/datetime.hxx>
33 #include <unotools/useroptions.hxx>
35 #include <resourcemanager.hxx>
36 #include <strings.hrc>
38 using namespace comphelper;
39 using namespace css;
41 CertificateChooser::CertificateChooser(weld::Window* _pParent,
42 std::vector< css::uno::Reference< css::xml::crypto::XXMLSecurityContext > > && rxSecurityContexts,
43 UserAction eAction)
44 : GenericDialogController(_pParent, "xmlsec/ui/selectcertificatedialog.ui", "SelectCertificateDialog")
45 , meAction(eAction)
46 , m_xFTSign(m_xBuilder->weld_label("sign"))
47 , m_xFTEncrypt(m_xBuilder->weld_label("encrypt"))
48 , m_xCertLB(m_xBuilder->weld_tree_view("signatures"))
49 , m_xViewBtn(m_xBuilder->weld_button("viewcert"))
50 , m_xOKBtn(m_xBuilder->weld_button("ok"))
51 , m_xFTDescription(m_xBuilder->weld_label("description-label"))
52 , m_xDescriptionED(m_xBuilder->weld_entry("description"))
54 auto nControlWidth = m_xCertLB->get_approximate_digit_width() * 105;
55 m_xCertLB->set_size_request(nControlWidth, m_xCertLB->get_height_rows(12));
57 std::vector<int> aWidths
59 o3tl::narrowing<int>(30*nControlWidth/100),
60 o3tl::narrowing<int>(30*nControlWidth/100),
61 o3tl::narrowing<int>(10*nControlWidth/100),
62 o3tl::narrowing<int>(20*nControlWidth/100)
64 m_xCertLB->set_column_fixed_widths(aWidths);
65 m_xCertLB->connect_changed( LINK( this, CertificateChooser, CertificateHighlightHdl ) );
66 m_xCertLB->connect_row_activated( LINK( this, CertificateChooser, CertificateSelectHdl ) );
67 m_xViewBtn->connect_clicked( LINK( this, CertificateChooser, ViewButtonHdl ) );
69 mxSecurityContexts = std::move(rxSecurityContexts);
70 mbInitialized = false;
72 // disable buttons
73 CertificateHighlightHdl(*m_xCertLB);
76 CertificateChooser::~CertificateChooser()
80 short CertificateChooser::run()
82 // #i48432#
83 // We can't check for personal certificates before raising this dialog,
84 // because the mozilla implementation throws a NoPassword exception,
85 // if the user pressed cancel, and also if the database does not exist!
86 // But in the later case, the is no password query, and the user is confused
87 // that nothing happens when pressing "Add..." in the SignatureDialog.
89 // PostUserEvent( LINK( this, CertificateChooser, Initialize ) );
91 // PostUserLink behavior is too slow, so do it directly before Execute().
92 // Problem: This Dialog should be visible right now, and the parent should not be accessible.
93 // Show, Update, DisableInput...
95 m_xDialog->show();
96 ImplInitialize();
97 return GenericDialogController::run();
100 void CertificateChooser::HandleOneUsageBit(OUString& string, int& bits, int bit, TranslateId pResId)
102 if (bits & bit)
104 if (!string.isEmpty())
105 string += ", ";
106 string += XsResId(pResId);
107 bits &= ~bit;
111 OUString CertificateChooser::UsageInClearText(int bits)
113 OUString result;
115 HandleOneUsageBit(result, bits, 0x80, STR_DIGITAL_SIGNATURE);
116 HandleOneUsageBit(result, bits, 0x40, STR_NON_REPUDIATION);
117 HandleOneUsageBit(result, bits, 0x20, STR_KEY_ENCIPHERMENT);
118 HandleOneUsageBit(result, bits, 0x10, STR_DATA_ENCIPHERMENT);
119 HandleOneUsageBit(result, bits, 0x08, STR_KEY_AGREEMENT);
120 HandleOneUsageBit(result, bits, 0x04, STR_KEY_CERT_SIGN);
121 HandleOneUsageBit(result, bits, 0x02, STR_CRL_SIGN);
122 HandleOneUsageBit(result, bits, 0x01, STR_ENCIPHER_ONLY);
124 // Check for mystery leftover bits
125 if (bits != 0)
127 if (!result.isEmpty())
128 result += ", ";
129 result += "0x" + OUString::number(bits, 16);
132 return result;
135 void CertificateChooser::ImplInitialize()
137 if ( mbInitialized )
138 return;
140 SvtUserOptions aUserOpts;
142 switch (meAction)
144 case UserAction::Sign:
145 m_xFTSign->show();
146 m_xOKBtn->set_label(XsResId(STR_SIGN));
147 msPreferredKey = aUserOpts.GetSigningKey();
148 break;
150 case UserAction::SelectSign:
151 m_xFTSign->show();
152 m_xOKBtn->set_label(XsResId(STR_SELECTSIGN));
153 msPreferredKey = aUserOpts.GetSigningKey();
154 break;
156 case UserAction::Encrypt:
157 m_xFTEncrypt->show();
158 m_xFTDescription->hide();
159 m_xDescriptionED->hide();
160 m_xCertLB->set_selection_mode(SelectionMode::Multiple);
161 m_xOKBtn->set_label(XsResId(STR_ENCRYPT));
162 msPreferredKey = aUserOpts.GetEncryptionKey();
163 break;
167 for (auto &secContext : mxSecurityContexts)
169 if (!secContext.is())
170 continue;
171 auto secEnvironment = secContext->getSecurityEnvironment();
172 if (!secEnvironment.is())
173 continue;
175 uno::Sequence< uno::Reference< security::XCertificate > > xCerts;
178 if ( meAction == UserAction::Sign || meAction == UserAction::SelectSign)
179 xCerts = secEnvironment->getPersonalCertificates();
180 else
181 xCerts = secEnvironment->getAllCertificates();
183 catch (security::NoPasswordException&)
187 for( sal_Int32 nCert = xCerts.getLength(); nCert; )
189 uno::Reference< security::XCertificate > xCert = xCerts[ --nCert ];
190 // Check if we have a private key for this...
191 tools::Long nCertificateCharacters = secEnvironment->getCertificateCharacters(xCert);
193 if (!(nCertificateCharacters & security::CertificateCharacters::HAS_PRIVATE_KEY))
195 ::comphelper::removeElementAt( xCerts, nCert );
200 // fill list of certificates; the first entry will be selected
201 for ( const auto& xCert : std::as_const(xCerts) )
203 std::shared_ptr<UserData> userData = std::make_shared<UserData>();
204 userData->xCertificate = xCert;
205 userData->xSecurityContext = secContext;
206 userData->xSecurityEnvironment = secEnvironment;
207 mvUserData.push_back(userData);
209 OUString sIssuer = xmlsec::GetContentPart( xCert->getIssuerName(), xCert->getCertificateKind());
211 m_xCertLB->append();
212 int nRow = m_xCertLB->n_children() - 1;
213 m_xCertLB->set_text(nRow, xmlsec::GetContentPart(xCert->getSubjectName(), xCert->getCertificateKind()), 0);
214 m_xCertLB->set_text(nRow, sIssuer, 1);
215 m_xCertLB->set_text(nRow, xmlsec::GetCertificateKind(xCert->getCertificateKind()), 2);
216 m_xCertLB->set_text(nRow, utl::GetDateString(xCert->getNotValidAfter()), 3);
217 m_xCertLB->set_text(nRow, UsageInClearText(xCert->getCertificateUsage()), 4);
218 OUString sId(weld::toId(userData.get()));
219 m_xCertLB->set_id(nRow, sId);
221 #if HAVE_FEATURE_GPGME
222 // only GPG has preferred keys
223 if ( !sIssuer.isEmpty() && !msPreferredKey.isEmpty() ) {
224 if ( sIssuer == msPreferredKey )
226 if ( meAction == UserAction::Sign || meAction == UserAction::SelectSign )
227 m_xCertLB->select(nRow);
228 else if ( meAction == UserAction::Encrypt &&
229 aUserOpts.GetEncryptToSelf() )
230 mxEncryptToSelf = xCert;
233 #endif
237 // enable/disable buttons
238 CertificateHighlightHdl(*m_xCertLB);
239 mbInitialized = true;
242 uno::Sequence<uno::Reference< css::security::XCertificate > > CertificateChooser::GetSelectedCertificates()
244 std::vector< uno::Reference< css::security::XCertificate > > aRet;
245 if (meAction == UserAction::Encrypt)
247 // for encryption, multiselection is enabled
248 m_xCertLB->selected_foreach([this, &aRet](weld::TreeIter& rEntry){
249 UserData* userData = weld::fromId<UserData*>(m_xCertLB->get_id(rEntry));
250 aRet.push_back( userData->xCertificate );
251 return false;
254 else
256 uno::Reference< css::security::XCertificate > xCert;
257 int nSel = m_xCertLB->get_selected_index();
258 if (nSel != -1)
260 UserData* userData = weld::fromId<UserData*>(m_xCertLB->get_id(nSel));
261 xCert = userData->xCertificate;
263 aRet.push_back( xCert );
266 #if HAVE_FEATURE_GPGME
267 if ( mxEncryptToSelf.is())
268 aRet.push_back( mxEncryptToSelf );
269 #endif
271 return comphelper::containerToSequence(aRet);
274 uno::Reference<xml::crypto::XXMLSecurityContext> CertificateChooser::GetSelectedSecurityContext() const
276 int nSel = m_xCertLB->get_selected_index();
277 if (nSel == -1)
278 return uno::Reference<xml::crypto::XXMLSecurityContext>();
280 UserData* userData = weld::fromId<UserData*>(m_xCertLB->get_id(nSel));
281 uno::Reference<xml::crypto::XXMLSecurityContext> xCert = userData->xSecurityContext;
282 return xCert;
285 OUString CertificateChooser::GetDescription() const
287 return m_xDescriptionED->get_text();
290 OUString CertificateChooser::GetUsageText()
292 uno::Sequence< uno::Reference<css::security::XCertificate> > xCerts =
293 GetSelectedCertificates();
294 return (xCerts.hasElements() && xCerts[0].is()) ?
295 UsageInClearText(xCerts[0]->getCertificateUsage()) : OUString();
298 IMPL_LINK_NOARG(CertificateChooser, CertificateHighlightHdl, weld::TreeView&, void)
300 bool bEnable = m_xCertLB->get_selected_index() != -1;
301 m_xViewBtn->set_sensitive(bEnable);
302 m_xOKBtn->set_sensitive(bEnable);
303 m_xDescriptionED->set_sensitive(bEnable);
306 IMPL_LINK_NOARG(CertificateChooser, CertificateSelectHdl, weld::TreeView&, bool)
308 m_xDialog->response(RET_OK);
309 return true;
312 IMPL_LINK_NOARG(CertificateChooser, ViewButtonHdl, weld::Button&, void)
314 ImplShowCertificateDetails();
317 void CertificateChooser::ImplShowCertificateDetails()
319 int nSel = m_xCertLB->get_selected_index();
320 if (nSel == -1)
321 return;
323 UserData* userData = weld::fromId<UserData*>(m_xCertLB->get_id(nSel));
325 if (!userData->xSecurityEnvironment.is() || !userData->xCertificate.is())
326 return;
328 CertificateViewer aViewer(m_xDialog.get(), userData->xSecurityEnvironment, userData->xCertificate, true, this);
329 aViewer.run();
332 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */