Debian Codegraph @

src/fdosecrets/objects/Service.cpp

raw
1 /*
2 * Copyright (C) 2018 Aetf <[email protected]>
3 *
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 2 or (at your option)
7 * version 3 of the License.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 */
17
18 #include "Service.h"
19
20 #include "fdosecrets/FdoSecretsPlugin.h"
21 #include "fdosecrets/FdoSecretsSettings.h"
22 #include "fdosecrets/objects/Collection.h"
23 #include "fdosecrets/objects/Item.h"
24 #include "fdosecrets/objects/Prompt.h"
25 #include "fdosecrets/objects/Session.h"
26
27 #include "gui/DatabaseTabWidget.h"
28 #include "gui/DatabaseWidget.h"
29
30 namespace
31 {
32 constexpr auto DEFAULT_ALIAS = "default";
33 }
34
35 namespace FdoSecrets
36 {
37 QSharedPointer<Service>
38 Service::Create(FdoSecretsPlugin* plugin, QPointer<DatabaseTabWidget> dbTabs, QSharedPointer<DBusMgr> dbus)
39 {
40 QSharedPointer<Service> res{new Service(plugin, std::move(dbTabs), std::move(dbus))};
41 if (!res->initialize()) {
42 return {};
43 }
44 return res;
45 }
46
47 Service::Service(FdoSecretsPlugin* plugin,
48 QPointer<DatabaseTabWidget> dbTabs,
49 QSharedPointer<DBusMgr> dbus) // clazy: exclude=ctor-missing-parent-argument
50 : DBusObject(std::move(dbus))
51 , m_plugin(plugin)
52 , m_databases(std::move(dbTabs))
53 , m_insideEnsureDefaultAlias(false)
54 {
55 connect(m_databases,
56 &DatabaseTabWidget::databaseUnlockDialogFinished,
57 this,
58 &Service::onDatabaseUnlockDialogFinished);
59 }
60
61 Service::~Service() = default;
62
63 bool Service::initialize()
64 {
65 if (!dbus()->registerObject(this)) {
66 return false;
67 }
68
69 // Add existing database tabs
70 for (int idx = 0; idx != m_databases->count(); ++idx) {
71 auto dbWidget = m_databases->databaseWidgetFromIndex(idx);
72 onDatabaseTabOpened(dbWidget, false);
73 }
74
75 // Connect to new database signal
76 // No need to connect to close signal, as collection will remove itself when backend delete/close database tab.
77 connect(m_databases.data(), &DatabaseTabWidget::databaseOpened, this, [this](DatabaseWidget* dbWidget) {
78 onDatabaseTabOpened(dbWidget, true);
79 });
80
81 // make default alias track current activated database
82 connect(m_databases.data(), &DatabaseTabWidget::activeDatabaseChanged, this, &Service::ensureDefaultAlias);
83
84 return true;
85 }
86
87 void Service::onDatabaseTabOpened(DatabaseWidget* dbWidget, bool emitSignal)
88 {
89 // The Collection will monitor the database's exposed group.
90 // When the Collection finds that no exposed group, it will delete itself.
91 // Thus, the service also needs to monitor it and recreate the collection if the user changes
92 // from no exposed to exposed something.
93 connect(dbWidget, &DatabaseWidget::databaseReplaced, this, [this, dbWidget]() {
94 monitorDatabaseExposedGroup(dbWidget);
95 });
96 if (!dbWidget->isLocked()) {
97 monitorDatabaseExposedGroup(dbWidget);
98 }
99
100 auto coll = Collection::Create(this, dbWidget);
101 if (!coll) {
102 return;
103 }
104
105 m_collections << coll;
106 m_dbToCollection[dbWidget] = coll;
107
108 // keep record of the collection existence
109 connect(coll, &Collection::collectionAboutToDelete, this, [this, coll]() {
110 m_collections.removeAll(coll);
111 m_dbToCollection.remove(coll->backend());
112 });
113
114 // keep record of alias
115 connect(coll, &Collection::aliasAboutToAdd, this, &Service::onCollectionAliasAboutToAdd);
116 connect(coll, &Collection::aliasAdded, this, &Service::onCollectionAliasAdded);
117 connect(coll, &Collection::aliasRemoved, this, &Service::onCollectionAliasRemoved);
118
119 // Forward delete signal, we have to rely on filepath to identify the database being closed,
120 // but we can not access m_backend safely because during the databaseClosed signal,
121 // m_backend may already be reset to nullptr
122 // We want to remove the collection object from dbus as early as possible, to avoid
123 // race conditions when deleteLater was called on the m_backend, but not delivered yet,
124 // and new method calls from dbus occurred. Therefore, we can't rely on the destroyed
125 // signal on m_backend.
126 // bind to coll lifespan
127 connect(m_databases.data(), &DatabaseTabWidget::databaseClosed, coll, [coll](const QString& filePath) {
128 if (filePath == coll->backendFilePath()) {
129 coll->removeFromDBus();
130 }
131 });
132
133 // actual load, must after updates to m_collections, because reloading may trigger
134 // another onDatabaseTabOpen, and m_collections will be used to prevent recursion.
135 if (!coll->reloadBackend()) {
136 // error in dbus
137 return;
138 }
139 if (!coll->backend()) {
140 // no exposed group on this db
141 return;
142 }
143
144 ensureDefaultAlias();
145
146 // only start relay signals when the collection is fully setup
147 connect(coll, &Collection::collectionChanged, this, [this, coll]() { emit collectionChanged(coll); });
148 connect(coll, &Collection::collectionAboutToDelete, this, [this, coll]() { emit collectionDeleted(coll); });
149 if (emitSignal) {
150 emit collectionCreated(coll);
151 }
152 }
153
154 void Service::monitorDatabaseExposedGroup(DatabaseWidget* dbWidget)
155 {
156 Q_ASSERT(dbWidget);
157 connect(dbWidget->database()->metadata()->customData(), &CustomData::modified, this, [this, dbWidget]() {
158 if (!FdoSecrets::settings()->exposedGroup(dbWidget->database()).isNull() && !findCollection(dbWidget)) {
159 onDatabaseTabOpened(dbWidget, true);
160 }
161 });
162 }
163
164 void Service::ensureDefaultAlias()
165 {
166 if (m_insideEnsureDefaultAlias) {
167 return;
168 }
169
170 m_insideEnsureDefaultAlias = true;
171
172 auto coll = findCollection(m_databases->currentDatabaseWidget());
173 if (coll) {
174 // adding alias will automatically remove the association with previous collection.
175 coll->addAlias(DEFAULT_ALIAS).okOrDie();
176 }
177
178 m_insideEnsureDefaultAlias = false;
179 }
180
181 DBusResult Service::collections(QList<Collection*>& collections) const
182 {
183 collections = m_collections;
184 return {};
185 }
186
187 DBusResult Service::unlockedCollections(QList<Collection*>& unlocked) const
188 {
189 auto ret = collections(unlocked);
190 if (ret.err()) {
191 return ret;
192 }
193
194 // filter out locked collections
195 auto it = unlocked.begin();
196 while (it != unlocked.end()) {
197 bool isLocked = true;
198 ret = (*it)->locked(isLocked);
199 if (ret.err()) {
200 return ret;
201 }
202 if (isLocked) {
203 it = unlocked.erase(it);
204 } else {
205 ++it;
206 }
207 }
208 return {};
209 }
210
211 DBusResult Service::openSession(const DBusClientPtr& client,
212 const QString& algorithm,
213 const QVariant& input,
214 QVariant& output,
215 Session*& result)
216 {
217 // negotiate cipher
218 bool incomplete = false;
219 auto ciphers = client->negotiateCipher(algorithm, input, output, incomplete);
220 if (incomplete) {
221 result = nullptr;
222 return {};
223 }
224 if (!ciphers) {
225 return QDBusError::NotSupported;
226 }
227
228 // create session using the negotiated cipher
229 result = Session::Create(std::move(ciphers), client->name(), this);
230 if (!result) {
231 return QDBusError::InternalError;
232 }
233
234 // remove session when the client disconnects
235 connect(dbus().data(), &DBusMgr::clientDisconnected, result, [result, client](const DBusClientPtr& toRemove) {
236 if (toRemove == client) {
237 result->close().okOrDie();
238 }
239 });
240
241 // keep a list of sessions
242 m_sessions.append(result);
243 connect(result, &Session::aboutToClose, this, [this, result]() { m_sessions.removeAll(result); });
244
245 return {};
246 }
247
248 DBusResult Service::createCollection(const QVariantMap& properties,
249 const QString& alias,
250 Collection*& collection,
251 PromptBase*& prompt)
252 {
253 prompt = nullptr;
254
255 // return existing collection if alias is non-empty and exists.
256 collection = findCollection(alias);
257 if (!collection) {
258 prompt = PromptBase::Create<CreateCollectionPrompt>(this, properties, alias);
259 if (!prompt) {
260 return QDBusError::InternalError;
261 }
262 }
263 return {};
264 }
265
266 DBusResult Service::searchItems(const DBusClientPtr& client,
267 const StringStringMap& attributes,
268 QList<Item*>& unlocked,
269 QList<Item*>& locked)
270 {
271 // we can only search unlocked collections
272 QList<Collection*> unlockedColls;
273 auto ret = unlockedCollections(unlockedColls);
274 if (ret.err()) {
275 return ret;
276 }
277
278 while (unlockedColls.isEmpty() && settings()->unlockBeforeSearch()) {
279 // enable compatibility mode by making sure at least one database is unlocked
280 QEventLoop loop;
281 bool wasAccepted = false;
282 connect(this, &Service::doneUnlockDatabaseInDialog, &loop, [&](bool accepted) {
283 wasAccepted = accepted;
284 loop.quit();
285 });
286
287 doUnlockAnyDatabaseInDialog();
288
289 // blocking wait
290 loop.exec();
291
292 if (!wasAccepted) {
293 // user cancelled, do not proceed
294 qWarning() << "user cancelled";
295 return {};
296 }
297
298 // need to recompute this because collections may disappear while in event loop
299 ret = unlockedCollections(unlockedColls);
300 if (ret.err()) {
301 return ret;
302 }
303 }
304
305 for (const auto& coll : asConst(unlockedColls)) {
306 QList<Item*> items;
307 ret = coll->searchItems(client, attributes, items);
308 if (ret.err()) {
309 return ret;
310 }
311 // item locked state already covers its collection's locked state
312 for (const auto& item : asConst(items)) {
313 Q_ASSERT(item);
314 bool itemLocked;
315 ret = item->locked(client, itemLocked);
316 if (ret.err()) {
317 return ret;
318 }
319 if (itemLocked) {
320 locked.append(item);
321 } else {
322 unlocked.append(item);
323 }
324 }
325 }
326 return {};
327 }
328
329 DBusResult Service::unlock(const DBusClientPtr& client,
330 const QList<DBusObject*>& objects,
331 QList<DBusObject*>& unlocked,
332 PromptBase*& prompt)
333 {
334 QSet<Collection*> collectionsToUnlock;
335 QSet<Item*> itemsToUnlock;
336 collectionsToUnlock.reserve(objects.size());
337 itemsToUnlock.reserve(objects.size());
338
339 for (const auto& obj : asConst(objects)) {
340 // the object is either an item or a collection
341 auto item = qobject_cast<Item*>(obj);
342 auto coll = item ? item->collection() : qobject_cast<Collection*>(obj);
343 // either way there should be a collection
344 if (!coll) {
345 continue;
346 }
347
348 bool collLocked{false}, itemLocked{false};
349 // if the collection needs unlock
350 auto ret = coll->locked(collLocked);
351 if (ret.err()) {
352 return ret;
353 }
354 if (collLocked) {
355 collectionsToUnlock << coll;
356 }
357
358 if (item) {
359 // item may also need unlock
360 ret = item->locked(client, itemLocked);
361 if (ret.err()) {
362 return ret;
363 }
364 if (itemLocked) {
365 itemsToUnlock << item;
366 }
367 }
368
369 // both collection and item are not locked
370 if (!collLocked && !itemLocked) {
371 unlocked << obj;
372 }
373 }
374
375 prompt = nullptr;
376 if (!collectionsToUnlock.isEmpty() || !itemsToUnlock.isEmpty()) {
377 prompt = PromptBase::Create<UnlockPrompt>(this, collectionsToUnlock, itemsToUnlock);
378 if (!prompt) {
379 return QDBusError::InternalError;
380 }
381 }
382 return {};
383 }
384
385 DBusResult Service::lock(const QList<DBusObject*>& objects, QList<DBusObject*>& locked, PromptBase*& prompt)
386 {
387 QSet<Collection*> needLock;
388 needLock.reserve(objects.size());
389 for (const auto& obj : asConst(objects)) {
390 auto coll = qobject_cast<Collection*>(obj);
391 if (coll) {
392 needLock << coll;
393 } else {
394 auto item = qobject_cast<Item*>(obj);
395 if (!item) {
396 continue;
397 }
398 // we lock the whole collection for item
399 needLock << item->collection();
400 }
401 }
402
403 // return anything already locked
404 QList<Collection*> toLock;
405 for (const auto& coll : asConst(needLock)) {
406 bool l;
407 auto ret = coll->locked(l);
408 if (ret.err()) {
409 return ret;
410 }
411 if (l) {
412 locked << coll;
413 } else {
414 toLock << coll;
415 }
416 }
417 if (!toLock.isEmpty()) {
418 prompt = PromptBase::Create<LockCollectionsPrompt>(this, toLock);
419 if (!prompt) {
420 return QDBusError::InternalError;
421 }
422 }
423 return {};
424 }
425
426 DBusResult Service::getSecrets(const DBusClientPtr& client,
427 const QList<Item*>& items,
428 Session* session,
429 ItemSecretMap& secrets) const
430 {
431 if (!session) {
432 return DBusResult(DBUS_ERROR_SECRET_NO_SESSION);
433 }
434
435 for (const auto& item : asConst(items)) {
436 auto ret = item->getSecretNoNotification(client, session, secrets[item]);
437 if (ret.err()) {
438 return ret;
439 }
440 }
441 plugin()->emitRequestShowNotification(
442 tr(R"(%n Entry(s) was used by %1)", "%1 is the name of an application", secrets.size())
443 .arg(client->name()));
444 return {};
445 }
446
447 DBusResult Service::readAlias(const QString& name, Collection*& collection) const
448 {
449 collection = findCollection(name);
450 return {};
451 }
452
453 DBusResult Service::setAlias(const QString& name, Collection* collection)
454 {
455 if (!collection) {
456 // remove alias name from its collection
457 collection = findCollection(name);
458 if (!collection) {
459 return DBusResult(DBUS_ERROR_SECRET_NO_SUCH_OBJECT);
460 }
461 return collection->removeAlias(name);
462 }
463 return collection->addAlias(name);
464 }
465
466 Collection* Service::findCollection(const QString& alias) const
467 {
468 if (alias.isEmpty()) {
469 return nullptr;
470 }
471
472 auto it = m_aliases.find(alias);
473 if (it != m_aliases.end()) {
474 return it.value();
475 }
476 return nullptr;
477 }
478
479 void Service::onCollectionAliasAboutToAdd(const QString& alias)
480 {
481 auto coll = qobject_cast<Collection*>(sender());
482
483 auto it = m_aliases.constFind(alias);
484 if (it != m_aliases.constEnd() && it.value() != coll) {
485 // another collection holds the alias
486 // remove it first
487 it.value()->removeAlias(alias).okOrDie();
488
489 // onCollectionAliasRemoved called through signal
490 // `it` becomes invalidated now
491 }
492 }
493
494 void Service::onCollectionAliasAdded(const QString& alias)
495 {
496 auto coll = qobject_cast<Collection*>(sender());
497 m_aliases[alias] = coll;
498 }
499
500 void Service::onCollectionAliasRemoved(const QString& alias)
501 {
502 m_aliases.remove(alias);
503 ensureDefaultAlias();
504 }
505
506 Collection* Service::findCollection(const DatabaseWidget* db) const
507 {
508 return m_dbToCollection.value(db, nullptr);
509 }
510
511 QList<Session*> Service::sessions() const
512 {
513 return m_sessions;
514 }
515
516 bool Service::doCloseDatabase(DatabaseWidget* dbWidget)
517 {
518 return m_databases->closeDatabaseTab(dbWidget);
519 }
520
521 Collection* Service::doNewDatabase()
522 {
523 auto dbWidget = m_databases->newDatabase();
524 if (!dbWidget) {
525 return nullptr;
526 }
527
528 // database created through dbus will be exposed to dbus by default
529 auto db = dbWidget->database();
530 FdoSecrets::settings()->setExposedGroup(db, db->rootGroup()->uuid());
531
532 auto collection = findCollection(dbWidget);
533
534 Q_ASSERT(collection);
535
536 return collection;
537 }
538
539 void Service::doSwitchToDatabaseSettings(DatabaseWidget* dbWidget)
540 {
541 if (dbWidget->isLocked()) {
542 return;
543 }
544 // switch selected to current
545 m_databases->setCurrentWidget(dbWidget);
546 m_databases->showDatabaseSettings(true);
547
548 // open settings (switch from app settings to m_dbTabs)
549 m_plugin->emitRequestSwitchToDatabases();
550 }
551
552 bool Service::doLockDatabase(DatabaseWidget* dbWidget)
553 {
554 // return immediately if the db is already unlocked
555 if (dbWidget && dbWidget->isLocked()) {
556 return true;
557 }
558
559 // mark the db as being unlocked to prevent multiple dialogs for the same db
560 if (m_lockingDb.contains(dbWidget)) {
561 return true;
562 }
563 m_lockingDb.insert(dbWidget);
564 auto ret = dbWidget->lock();
565 m_lockingDb.remove(dbWidget);
566
567 return ret;
568 }
569
570 void Service::doUnlockDatabaseInDialog(DatabaseWidget* dbWidget)
571 {
572 // return immediately if the db is already unlocked
573 if (dbWidget && !dbWidget->isLocked()) {
574 emit doneUnlockDatabaseInDialog(true, dbWidget);
575 return;
576 }
577
578 // check if the db is already being unlocked to prevent multiple dialogs for the same db
579 if (m_unlockingAnyDatabase || m_unlockingDb.contains(dbWidget)) {
580 return;
581 }
582
583 // insert a dummy one here, just to prevent multiple dialogs
584 // the real one will be inserted in onDatabaseUnlockDialogFinished
585 m_unlockingDb[dbWidget] = {};
586
587 // actually show the dialog
588 m_databases->unlockDatabaseInDialog(dbWidget, DatabaseOpenDialog::Intent::None);
589 }
590
591 void Service::doUnlockAnyDatabaseInDialog()
592 {
593 if (m_unlockingAnyDatabase || !m_unlockingDb.isEmpty()) {
594 return;
595 }
596 m_unlockingAnyDatabase = true;
597
598 m_databases->unlockAnyDatabaseInDialog(DatabaseOpenDialog::Intent::None);
599 }
600
601 void Service::onDatabaseUnlockDialogFinished(bool accepted, DatabaseWidget* dbWidget)
602 {
603 if (!m_unlockingAnyDatabase && !m_unlockingDb.contains(dbWidget)) {
604 // not our concern
605 return;
606 }
607
608 if (!accepted) {
609 emit doneUnlockDatabaseInDialog(false, dbWidget);
610 m_unlockingAnyDatabase = false;
611 m_unlockingDb.remove(dbWidget);
612 } else {
613 // delay the done signal to when the database is actually done with unlocking
614 // this is a oneshot connection to prevent superfluous signals
615 auto conn = connect(dbWidget, &DatabaseWidget::databaseUnlocked, this, [dbWidget, this]() {
616 emit doneUnlockDatabaseInDialog(true, dbWidget);
617 m_unlockingAnyDatabase = false;
618 disconnect(m_unlockingDb.take(dbWidget));
619 });
620 m_unlockingDb[dbWidget] = conn;
621 }
622 }
623 } // namespace FdoSecrets