Debian Codegraph @

src/fdosecrets/objects/Collection.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 "Collection.h"
19
20 #include "fdosecrets/FdoSecretsSettings.h"
21 #include "fdosecrets/objects/Item.h"
22 #include "fdosecrets/objects/Prompt.h"
23 #include "fdosecrets/objects/Service.h"
24
25 #include "core/Tools.h"
26 #include "gui/DatabaseWidget.h"
27 #include "gui/GuiTools.h"
28
29 #include <QEventLoop>
30 #include <QFileInfo>
31
32 namespace FdoSecrets
33 {
34 Collection* Collection::Create(Service* parent, DatabaseWidget* backend)
35 {
36 return new Collection(parent, backend);
37 }
38
39 Collection::Collection(Service* parent, DatabaseWidget* backend)
40 : DBusObject(parent)
41 , m_backend(backend)
42 , m_exposedGroup(nullptr)
43 {
44 // whenever the file path or the database object itself change, we do a full reload.
45 connect(backend, &DatabaseWidget::databaseFilePathChanged, this, &Collection::reloadBackendOrDelete);
46 connect(backend, &DatabaseWidget::databaseReplaced, this, &Collection::reloadBackendOrDelete);
47
48 // also remember to clear/populate the database when lock state changes.
49 connect(backend, &DatabaseWidget::databaseUnlocked, this, &Collection::onDatabaseLockChanged);
50 connect(backend, &DatabaseWidget::databaseLocked, this, &Collection::onDatabaseLockChanged);
51
52 // get notified whenever unlock db dialog finishes
53 connect(parent, &Service::doneUnlockDatabaseInDialog, this, [this](bool accepted, DatabaseWidget* dbWidget) {
54 if (!dbWidget || dbWidget != m_backend) {
55 return;
56 }
57 emit doneUnlockCollection(accepted);
58 });
59 }
60
61 bool Collection::reloadBackend()
62 {
63 Q_ASSERT(m_backend);
64
65 // delete all items
66 // this has to be done because the backend is actually still there, just we don't expose them
67 // NOTE: Do NOT use a for loop, because Item::removeFromDBus will remove itself from m_items.
68 while (!m_items.isEmpty()) {
69 m_items.first()->removeFromDBus();
70 }
71 cleanupConnections();
72 dbus()->unregisterObject(this);
73
74 // make sure we have updated copy of the filepath, which is used to identify the database.
75 m_backendPath = m_backend->database()->canonicalFilePath();
76
77 // register the object, handling potentially duplicated name
78 if (!dbus()->registerObject(this)) {
79 return false;
80 }
81
82 // populate contents after expose on dbus, because items rely on parent's dbus object path
83 if (!backendLocked()) {
84 populateContents();
85 } else {
86 cleanupConnections();
87 }
88
89 emit collectionChanged();
90 return true;
91 }
92
93 void Collection::reloadBackendOrDelete()
94 {
95 if (!reloadBackend()) {
96 removeFromDBus();
97 }
98 }
99
100 DBusResult Collection::ensureBackend() const
101 {
102 if (!m_backend) {
103 return DBusResult(DBUS_ERROR_SECRET_NO_SUCH_OBJECT);
104 }
105 return {};
106 }
107
108 DBusResult Collection::ensureUnlocked() const
109 {
110 if (backendLocked()) {
111 return DBusResult(DBUS_ERROR_SECRET_IS_LOCKED);
112 }
113 return {};
114 }
115
116 DBusResult Collection::items(QList<Item*>& items) const
117 {
118 auto ret = ensureBackend();
119 if (ret.err()) {
120 return ret;
121 }
122 items = m_items;
123 return {};
124 }
125
126 DBusResult Collection::label(QString& label) const
127 {
128 auto ret = ensureBackend();
129 if (ret.err()) {
130 return ret;
131 }
132
133 if (backendLocked()) {
134 label = name();
135 } else {
136 label = m_backend->database()->metadata()->name();
137 }
138 return {};
139 }
140
141 DBusResult Collection::setLabel(const QString& label)
142 {
143 auto ret = ensureBackend();
144 if (ret.err()) {
145 return ret;
146 }
147 ret = ensureUnlocked();
148 if (ret.err()) {
149 return ret;
150 }
151
152 m_backend->database()->metadata()->setName(label);
153 return {};
154 }
155
156 DBusResult Collection::locked(bool& locked) const
157 {
158 auto ret = ensureBackend();
159 if (ret.err()) {
160 return ret;
161 }
162 locked = backendLocked();
163 return {};
164 }
165
166 DBusResult Collection::created(qulonglong& created) const
167 {
168 auto ret = ensureBackend();
169 if (ret.err()) {
170 return ret;
171 }
172 ret = ensureUnlocked();
173 if (ret.err()) {
174 return ret;
175 }
176 created = static_cast<qulonglong>(
177 m_backend->database()->rootGroup()->timeInfo().creationTime().toMSecsSinceEpoch() / 1000);
178
179 return {};
180 }
181
182 DBusResult Collection::modified(qulonglong& modified) const
183 {
184 auto ret = ensureBackend();
185 if (ret.err()) {
186 return ret;
187 }
188 ret = ensureUnlocked();
189 if (ret.err()) {
190 return ret;
191 }
192 // FIXME: there seems not to have a global modified time.
193 // Use a more accurate time, considering all metadata, group, entry.
194 modified = static_cast<qulonglong>(
195 m_backend->database()->rootGroup()->timeInfo().lastModificationTime().toMSecsSinceEpoch() / 1000);
196 return {};
197 }
198
199 DBusResult Collection::remove(PromptBase*& prompt)
200 {
201 auto ret = ensureBackend();
202 if (ret.err()) {
203 return ret;
204 }
205
206 prompt = PromptBase::Create<DeleteCollectionPrompt>(service(), this);
207 if (!prompt) {
208 return QDBusError::InternalError;
209 }
210 return {};
211 }
212
213 DBusResult Collection::searchItems(const DBusClientPtr&, const StringStringMap& attributes, QList<Item*>& items)
214 {
215 items.clear();
216
217 auto ret = ensureBackend();
218 if (ret.err()) {
219 return ret;
220 }
221
222 if (backendLocked()) {
223 // searchItems should work, whether `this` is locked or not.
224 // however, we can't search items the same way as in gnome-keying,
225 // because there's no database at all when locked.
226 return {};
227 }
228
229 // shortcut logic for Uuid/Path attributes, as they can uniquely identify an item.
230 if (attributes.contains(ItemAttributes::UuidKey)) {
231 auto uuid = QUuid::fromRfc4122(QByteArray::fromHex(attributes.value(ItemAttributes::UuidKey).toLatin1()));
232 auto entry = m_exposedGroup->findEntryByUuid(uuid);
233 if (entry) {
234 items += m_entryToItem.value(entry);
235 }
236 return {};
237 }
238
239 if (attributes.contains(ItemAttributes::PathKey)) {
240 auto path = attributes.value(ItemAttributes::PathKey);
241 auto entry = m_exposedGroup->findEntryByPath(path);
242 if (entry) {
243 items += m_entryToItem.value(entry);
244 }
245 return {};
246 }
247
248 QList<EntrySearcher::SearchTerm> terms;
249 for (auto it = attributes.constBegin(); it != attributes.constEnd(); ++it) {
250 terms << attributeToTerm(it.key(), it.value());
251 }
252
253 constexpr auto caseSensitive = false;
254 constexpr auto skipProtected = true;
255 constexpr auto forceSearch = true;
256 const auto foundEntries =
257 EntrySearcher(caseSensitive, skipProtected).search(terms, m_exposedGroup, forceSearch);
258 items.reserve(foundEntries.size());
259 for (const auto& entry : foundEntries) {
260 const auto item = m_entryToItem.value(entry);
261 // it's possible that we don't have a corresponding item for the entry
262 // this can happen when the recycle bin is below the exposed group.
263 if (item) {
264 items << item;
265 }
266 }
267 return {};
268 }
269
270 EntrySearcher::SearchTerm Collection::attributeToTerm(const QString& key, const QString& value)
271 {
272 static QMap<QString, EntrySearcher::Field> attrKeyToField{
273 {EntryAttributes::TitleKey, EntrySearcher::Field::Title},
274 {EntryAttributes::UserNameKey, EntrySearcher::Field::Username},
275 {EntryAttributes::URLKey, EntrySearcher::Field::Url},
276 {EntryAttributes::NotesKey, EntrySearcher::Field::Notes},
277 };
278
279 EntrySearcher::SearchTerm term{};
280 term.field = attrKeyToField.value(key, EntrySearcher::Field::AttributeValue);
281 term.word = key;
282 term.exclude = false;
283 term.regex =
284 Tools::convertToRegex(value,
285 Tools::RegexConvertOpts::EXACT_MATCH | Tools::RegexConvertOpts::CASE_SENSITIVE
286 | Tools::RegexConvertOpts::ESCAPE_REGEX);
287
288 return term;
289 }
290
291 DBusResult Collection::createItem(const QVariantMap& properties,
292 const Secret& secret,
293 bool replace,
294 Item*& item,
295 PromptBase*& prompt)
296 {
297 auto ret = ensureBackend();
298 if (ret.err()) {
299 return ret;
300 }
301
302 item = nullptr;
303
304 prompt = PromptBase::Create<CreateItemPrompt>(service(), this, properties, secret, replace);
305 if (!prompt) {
306 return QDBusError::InternalError;
307 }
308 return {};
309 }
310
311 DBusResult Collection::setProperties(const QVariantMap& properties)
312 {
313 auto label = properties.value(DBUS_INTERFACE_SECRET_COLLECTION + ".Label").toString();
314
315 auto ret = setLabel(label);
316 if (ret.err()) {
317 return ret;
318 }
319
320 return {};
321 }
322
323 const QSet<QString> Collection::aliases() const
324 {
325 return m_aliases;
326 }
327
328 DBusResult Collection::addAlias(QString alias)
329 {
330 auto ret = ensureBackend();
331 if (ret.err()) {
332 return ret;
333 }
334
335 alias = encodePath(alias);
336
337 if (m_aliases.contains(alias)) {
338 return {};
339 }
340
341 emit aliasAboutToAdd(alias);
342
343 if (dbus()->registerAlias(this, alias)) {
344 m_aliases.insert(alias);
345 emit aliasAdded(alias);
346 } else {
347 return QDBusError::InvalidObjectPath;
348 }
349
350 return {};
351 }
352
353 DBusResult Collection::removeAlias(QString alias)
354 {
355 auto ret = ensureBackend();
356 if (ret.err()) {
357 return ret;
358 }
359
360 alias = encodePath(alias);
361
362 if (!m_aliases.contains(alias)) {
363 return {};
364 }
365
366 dbus()->unregisterAlias(alias);
367 m_aliases.remove(alias);
368 emit aliasRemoved(alias);
369
370 return {};
371 }
372
373 QString Collection::name() const
374 {
375 if (m_backendPath.isEmpty()) {
376 // This is a newly created db without saving to file,
377 // but we have to give a name, which is used to register dbus path.
378 // We use database name for this purpose. For simplicity, we don't monitor the name change.
379 // So the dbus object path is not updated if the db name changes.
380 // This should not be a problem because once the database gets saved,
381 // the dbus path will be updated to use filename and everything back to normal.
382 return m_backend->database()->metadata()->name();
383 }
384 return QFileInfo(m_backendPath).completeBaseName();
385 }
386
387 DatabaseWidget* Collection::backend() const
388 {
389 return m_backend;
390 }
391
392 void Collection::onDatabaseLockChanged()
393 {
394 if (!reloadBackend()) {
395 removeFromDBus();
396 return;
397 }
398 emit collectionLockChanged(backendLocked());
399 }
400
401 void Collection::populateContents()
402 {
403 if (!m_backend) {
404 return;
405 }
406
407 // we have an unlocked db
408
409 auto newUuid = FdoSecrets::settings()->exposedGroup(m_backend->database());
410 auto newGroup = m_backend->database()->rootGroup()->findGroupByUuid(newUuid);
411 if (!newGroup || newGroup->isRecycled()) {
412 // no exposed group, delete self
413 removeFromDBus();
414 return;
415 }
416
417 // clean up old group connections
418 cleanupConnections();
419
420 m_exposedGroup = newGroup;
421
422 // Attach signal to update exposed group settings if the group was removed.
423 //
424 // When the group object is normally deleted due to ~Database, the databaseReplaced
425 // signal should be first emitted, and we will clean up connection in reloadDatabase,
426 // so this handler won't be triggered.
427 connect(m_exposedGroup.data(), &Group::groupAboutToRemove, this, [this](Group* toBeRemoved) {
428 if (backendLocked()) {
429 return;
430 }
431 auto db = m_backend->database();
432 if (toBeRemoved->database() != db) {
433 // should not happen, but anyway.
434 // somehow our current database has been changed, and the old group is being deleted
435 // possibly logic changes in replaceDatabase.
436 return;
437 }
438 auto uuid = FdoSecrets::settings()->exposedGroup(db);
439 auto exposedGroup = db->rootGroup()->findGroupByUuid(uuid);
440 if (toBeRemoved == exposedGroup) {
441 // reset the exposed group to none
442 FdoSecrets::settings()->setExposedGroup(db, {});
443 }
444 });
445 // Another possibility is the group being moved to recycle bin.
446 connect(m_exposedGroup.data(), &Group::modified, this, [this]() {
447 if (m_exposedGroup->isRecycled()) {
448 // reset the exposed group to none
449 FdoSecrets::settings()->setExposedGroup(m_backend->database().data(), {});
450 }
451 });
452
453 // Monitor exposed group settings
454 connect(m_backend->database()->metadata()->customData(), &CustomData::modified, this, [this]() {
455 if (!m_exposedGroup || backendLocked()) {
456 return;
457 }
458 if (m_exposedGroup->uuid() == FdoSecrets::settings()->exposedGroup(m_backend->database())) {
459 // no change
460 return;
461 }
462 onDatabaseExposedGroupChanged();
463 });
464
465 // Add items for existing entry
466 const auto entries = m_exposedGroup->entriesRecursive(false);
467 for (const auto& entry : entries) {
468 onEntryAdded(entry, false);
469 }
470
471 // Do not connect to Database::modified signal because we only want signals for the subset under m_exposedGroup
472 connect(m_backend->database()->metadata(), &Metadata::modified, this, &Collection::collectionChanged);
473 connectGroupSignalRecursive(m_exposedGroup);
474 }
475
476 void Collection::onDatabaseExposedGroupChanged()
477 {
478 // delete all items
479 // this has to be done because the backend is actually still there
480 // just we don't expose them
481 for (const auto& item : asConst(m_items)) {
482 item->removeFromDBus();
483 }
484
485 // repopulate
486 if (!backendLocked()) {
487 populateContents();
488 }
489 }
490
491 void Collection::onEntryAdded(Entry* entry, bool emitSignal)
492 {
493 if (entry->isRecycled()) {
494 return;
495 }
496
497 auto item = Item::Create(this, entry);
498 if (!item) {
499 return;
500 }
501
502 m_items << item;
503 m_entryToItem[entry] = item;
504
505 // forward delete signals
506 connect(entry->group(), &Group::entryAboutToRemove, item, [item](Entry* toBeRemoved) {
507 if (item->backend() == toBeRemoved) {
508 item->removeFromDBus();
509 }
510 });
511
512 // relay signals
513 connect(item, &Item::itemChanged, this, [this, item]() { emit itemChanged(item); });
514 connect(item, &Item::itemAboutToDelete, this, [this, item]() {
515 m_items.removeAll(item);
516 m_entryToItem.remove(item->backend());
517 emit itemDeleted(item);
518 });
519
520 if (emitSignal) {
521 emit itemCreated(item);
522 }
523 }
524
525 void Collection::connectGroupSignalRecursive(Group* group)
526 {
527 if (group->isRecycled()) {
528 return;
529 }
530
531 connect(group, &Group::modified, this, &Collection::collectionChanged);
532 connect(group, &Group::entryAdded, this, [this](Entry* entry) { onEntryAdded(entry, true); });
533
534 const auto children = group->children();
535 for (const auto& cg : children) {
536 connectGroupSignalRecursive(cg);
537 }
538 }
539
540 Service* Collection::service() const
541 {
542 return qobject_cast<Service*>(parent());
543 }
544
545 bool Collection::doLock()
546 {
547 Q_ASSERT(m_backend);
548
549 // do not call m_backend->lock() directly
550 // let the service handle locking which handles concurrent calls
551 return service()->doLockDatabase(m_backend);
552 }
553
554 void Collection::doUnlock()
555 {
556 Q_ASSERT(m_backend);
557
558 return service()->doUnlockDatabaseInDialog(m_backend);
559 }
560
561 bool Collection::doDelete()
562 {
563 Q_ASSERT(m_backend);
564
565 return service()->doCloseDatabase(m_backend);
566 }
567
568 void Collection::removeFromDBus()
569 {
570 if (!m_backend) {
571 // I'm already deleted
572 return;
573 }
574
575 emit collectionAboutToDelete();
576
577 // remove from dbus early
578 dbus()->unregisterObject(this);
579
580 // remove alias manually to trigger signal
581 for (const auto& a : aliases()) {
582 removeAlias(a).okOrDie();
583 }
584
585 // cleanup connection on Database
586 cleanupConnections();
587 // cleanup connection on Backend itself
588 m_backend->disconnect(this);
589 parent()->disconnect(this);
590
591 m_exposedGroup = nullptr;
592
593 // reset backend and delete self
594 m_backend = nullptr;
595 deleteLater();
596
597 // items will be removed automatically as they are children objects
598 }
599
600 void Collection::cleanupConnections()
601 {
602 m_backend->database()->metadata()->customData()->disconnect(this);
603 if (m_exposedGroup) {
604 for (const auto group : m_exposedGroup->groupsRecursive(true)) {
605 group->disconnect(this);
606 }
607 }
608
609 m_items.clear();
610 }
611
612 QString Collection::backendFilePath() const
613 {
614 return m_backendPath;
615 }
616
617 Group* Collection::exposedRootGroup() const
618 {
619 return m_exposedGroup;
620 }
621
622 bool Collection::backendLocked() const
623 {
624 return !m_backend || !m_backend->database()->isInitialized() || m_backend->isLocked();
625 }
626
627 bool Collection::doDeleteEntry(Entry* entry)
628 {
629 // Confirm entry removal before moving forward
630 bool permanent = entry->isRecycled() || !m_backend->database()->metadata()->recycleBinEnabled();
631 if (FdoSecrets::settings()->confirmDeleteItem()
632 && !GuiTools::confirmDeleteEntries(m_backend, {entry}, permanent)) {
633 return false;
634 }
635
636 auto num = GuiTools::deleteEntriesResolveReferences(m_backend, {entry}, permanent);
637
638 return num != 0;
639 }
640
641 Group* Collection::findCreateGroupByPath(const QString& groupPath)
642 {
643 auto group = m_exposedGroup->findGroupByPath(groupPath);
644 if (group) {
645 return group;
646 }
647
648 // groupPath can't be empty here, because otherwise it will match m_exposedGroup and was returned above
649 Q_ASSERT(!groupPath.isEmpty());
650
651 auto groups = groupPath.split('/', QString::SkipEmptyParts);
652 auto groupName = groups.takeLast();
653
654 // create parent group
655 auto parentGroup = findCreateGroupByPath(groups.join('/'));
656
657 // create this group
658 group = new Group();
659 group->setUuid(QUuid::createUuid());
660 group->setName(groupName);
661 group->setIcon(Group::DefaultIconNumber);
662 group->setParent(parentGroup);
663
664 return group;
665 }
666
667 Item* Collection::doNewItem(const DBusClientPtr& client, QString itemPath)
668 {
669 Q_ASSERT(m_backend);
670
671 // normalize itemPath
672 itemPath = (itemPath.startsWith('/') ? QString{} : QStringLiteral("/")) + itemPath;
673
674 // split itemPath to groupPath and itemName
675 auto components = itemPath.split('/');
676 Q_ASSERT(components.size() >= 2);
677
678 auto itemName = components.takeLast();
679 Group* group = findCreateGroupByPath(components.join('/'));
680
681 // create new Entry in backend
682 auto* entry = new Entry();
683 entry->setUuid(QUuid::createUuid());
684 entry->setTitle(itemName);
685 entry->setUsername(m_backend->database()->metadata()->defaultUserName());
686 group->applyGroupIconOnCreateTo(entry);
687
688 entry->setGroup(group);
689
690 // the item was just created so there is no point in having it not authorized
691 client->setItemAuthorized(entry->uuid(), AuthDecision::Allowed);
692
693 // when creation finishes in backend, we will already have item
694 auto created = m_entryToItem.value(entry, nullptr);
695
696 return created;
697 }
698
699 } // namespace FdoSecrets