Welcome to mirror list, hosted at ThFree Co, Russian Federation.

Collection.cpp « objects « fdosecrets « src - github.com/keepassxreboot/keepassxc.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: ccf88cecc3dae845d06edb632bcb2d94ca0d98eb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
/*
 *  Copyright (C) 2018 Aetf <aetf@unlimitedcodeworks.xyz>
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 2 or (at your option)
 *  version 3 of the License.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "Collection.h"

#include "fdosecrets/FdoSecretsSettings.h"
#include "fdosecrets/objects/Item.h"
#include "fdosecrets/objects/Prompt.h"
#include "fdosecrets/objects/Service.h"

#include "core/Config.h"
#include "core/Database.h"
#include "core/EntrySearcher.h"
#include "gui/DatabaseTabWidget.h"
#include "gui/DatabaseWidget.h"

#include <QFileInfo>

namespace FdoSecrets
{

    Collection::Collection(Service* parent, DatabaseWidget* backend)
        : DBusObject(parent)
        , m_backend(backend)
        , m_exposedGroup(nullptr)
        , m_registered(false)
    {
        // whenever the file path or the database object itself change, we do a full reload.
        connect(backend, &DatabaseWidget::databaseFilePathChanged, this, &Collection::reloadBackend);
        connect(backend, &DatabaseWidget::databaseReplaced, this, &Collection::reloadBackend);

        // also remember to clear/populate the database when lock state changes.
        connect(backend, &DatabaseWidget::databaseUnlocked, this, &Collection::onDatabaseLockChanged);
        connect(backend, &DatabaseWidget::databaseLocked, this, &Collection::onDatabaseLockChanged);

        reloadBackend();
    }

    void Collection::reloadBackend()
    {
        if (m_registered) {
            // delete all items
            // this has to be done because the backend is actually still there, just we don't expose them
            // NOTE: Do NOT use a for loop, because Item::doDelete will remove itself from m_items.
            while (!m_items.isEmpty()) {
                m_items.first()->doDelete();
            }
            cleanupConnections();

            unregisterCurrentPath();
            m_registered = false;
        }

        // make sure we have updated copy of the filepath, which is used to identify the database.
        m_backendPath = m_backend->database()->filePath();

        // the database may not have a name (derived from filePath) yet, which may happen if it's newly created.
        // defer the registration to next time a file path change happens.
        if (!name().isEmpty()) {
            registerWithPath(
                QStringLiteral(DBUS_PATH_TEMPLATE_COLLECTION).arg(p()->objectPath().path(), encodePath(name())),
                new CollectionAdaptor(this));
            m_registered = true;
        }

        // populate contents after expose on dbus, because items rely on parent's dbus object path
        if (!backendLocked()) {
            populateContents();
        } else {
            cleanupConnections();
        }
    }

    DBusReturn<void> Collection::ensureBackend() const
    {
        if (!m_backend) {
            return DBusReturn<>::Error(QStringLiteral(DBUS_ERROR_SECRET_NO_SUCH_OBJECT));
        }
        return {};
    }

    DBusReturn<void> Collection::ensureUnlocked() const
    {
        if (backendLocked()) {
            return DBusReturn<>::Error(QStringLiteral(DBUS_ERROR_SECRET_IS_LOCKED));
        }
        return {};
    }

    DBusReturn<const QList<Item*>> Collection::items() const
    {
        auto ret = ensureBackend();
        if (ret.isError()) {
            return ret;
        }
        return m_items;
    }

    DBusReturn<QString> Collection::label() const
    {
        auto ret = ensureBackend();
        if (ret.isError()) {
            return ret;
        }

        if (backendLocked()) {
            return name();
        }
        return m_backend->database()->metadata()->name();
    }

    DBusReturn<void> Collection::setLabel(const QString& label)
    {
        auto ret = ensureBackend();
        if (ret.isError()) {
            return ret;
        }
        ret = ensureUnlocked();
        if (ret.isError()) {
            return ret;
        }

        m_backend->database()->metadata()->setName(label);
        return {};
    }

    DBusReturn<bool> Collection::locked() const
    {
        auto ret = ensureBackend();
        if (ret.isError()) {
            return ret;
        }
        return backendLocked();
    }

    DBusReturn<qulonglong> Collection::created() const
    {
        auto ret = ensureBackend();
        if (ret.isError()) {
            return ret;
        }
        ret = ensureUnlocked();
        if (ret.isError()) {
            return ret;
        }
        return static_cast<qulonglong>(m_backend->database()->rootGroup()->timeInfo().creationTime().toMSecsSinceEpoch()
                                       / 1000);
    }

    DBusReturn<qulonglong> Collection::modified() const
    {
        auto ret = ensureBackend();
        if (ret.isError()) {
            return ret;
        }
        ret = ensureUnlocked();
        if (ret.isError()) {
            return ret;
        }
        // FIXME: there seems not to have a global modified time.
        // Use a more accurate time, considering all metadata, group, entry.
        return static_cast<qulonglong>(
            m_backend->database()->rootGroup()->timeInfo().lastModificationTime().toMSecsSinceEpoch() / 1000);
    }

    DBusReturn<PromptBase*> Collection::deleteCollection()
    {
        auto ret = ensureBackend();
        if (ret.isError()) {
            return ret;
        }

        // Delete means close database
        auto prompt = new DeleteCollectionPrompt(service(), this);
        if (backendLocked()) {
            // this won't raise a dialog, immediate execute
            auto pret = prompt->prompt({});
            if (pret.isError()) {
                return pret;
            }
            prompt = nullptr;
        }
        // defer the close to the prompt
        return prompt;
    }

    DBusReturn<const QList<Item*>> Collection::searchItems(const StringStringMap& attributes)
    {
        auto ret = ensureBackend();
        if (ret.isError()) {
            return ret;
        }
        ret = ensureUnlocked();
        if (ret.isError()) {
            // searchItems should work, whether `this` is locked or not.
            // however, we can't search items the same way as in gnome-keying,
            // because there's no database at all when locked.
            return QList<Item*>{};
        }

        // shortcut logic for Uuid/Path attributes, as they can uniquely identify an item.
        if (attributes.contains(ItemAttributes::UuidKey)) {
            auto uuid = QUuid::fromRfc4122(QByteArray::fromHex(attributes.value(ItemAttributes::UuidKey).toLatin1()));
            auto entry = m_exposedGroup->findEntryByUuid(uuid);
            if (entry) {
                return QList<Item*>{m_entryToItem.value(entry)};
            } else {
                return QList<Item*>{};
            }
        }

        if (attributes.contains(ItemAttributes::PathKey)) {
            auto path = attributes.value(ItemAttributes::PathKey);
            auto entry = m_exposedGroup->findEntryByPath(path);
            if (entry) {
                return QList<Item*>{m_entryToItem.value(entry)};
            } else {
                return QList<Item*>{};
            }
        }

        static QMap<QString, QString> attrKeyToField{
            {EntryAttributes::TitleKey, QStringLiteral("title")},
            {EntryAttributes::UserNameKey, QStringLiteral("user")},
            {EntryAttributes::URLKey, QStringLiteral("url")},
            {EntryAttributes::NotesKey, QStringLiteral("notes")},
        };

        QStringList terms;
        for (auto it = attributes.constBegin(); it != attributes.constEnd(); ++it) {
            if (it.key() == EntryAttributes::PasswordKey) {
                continue;
            }
            auto field = attrKeyToField.value(it.key(), QStringLiteral("_") + Item::encodeAttributeKey(it.key()));
            terms << QStringLiteral(R"raw(+%1:"%2")raw").arg(field, it.value());
        }

        QList<Item*> items;
        const auto foundEntries = EntrySearcher().search(terms.join(' '), m_exposedGroup);
        items.reserve(foundEntries.size());
        for (const auto& entry : foundEntries) {
            items << m_entryToItem.value(entry);
        }
        return items;
    }

    DBusReturn<Item*>
    Collection::createItem(const QVariantMap& properties, const SecretStruct& secret, bool replace, PromptBase*& prompt)
    {
        auto ret = ensureBackend();
        if (ret.isError()) {
            return ret;
        }
        ret = ensureUnlocked();
        if (ret.isError()) {
            return ret;
        }

        prompt = nullptr;

        Item* item = nullptr;
        QString itemPath;
        StringStringMap attributes;

        // check existing item using attributes
        auto iterAttr = properties.find(QStringLiteral(DBUS_INTERFACE_SECRET_ITEM ".Attributes"));
        if (iterAttr != properties.end()) {
            attributes = qdbus_cast<StringStringMap>(iterAttr.value().value<QDBusArgument>());

            itemPath = attributes.value(ItemAttributes::PathKey);

            auto existings = searchItems(attributes);
            if (existings.isError()) {
                return existings;
            }
            if (!existings.value().isEmpty() && replace) {
                item = existings.value().front();
            }
        }

        if (!item) {
            // normalize itemPath
            itemPath = itemPath.startsWith('/') ? QString{} : QStringLiteral("/") + itemPath;

            // split itemPath to groupPath and itemName
            auto components = itemPath.split('/');
            Q_ASSERT(components.size() >= 2);

            auto itemName = components.takeLast();
            Group* group = findCreateGroupByPath(components.join('/'));

            // create new Entry in backend
            auto* entry = new Entry();
            entry->setUuid(QUuid::createUuid());
            entry->setTitle(itemName);
            entry->setUsername(m_backend->database()->metadata()->defaultUserName());
            group->applyGroupIconOnCreateTo(entry);

            entry->setGroup(group);

            // when creation finishes in backend, we will already have item
            item = m_entryToItem.value(entry, nullptr);
            Q_ASSERT(item);
        }

        ret = item->setProperties(properties);
        if (ret.isError()) {
            return ret;
        }
        ret = item->setSecret(secret);
        if (ret.isError()) {
            return ret;
        }

        return item;
    }

    DBusReturn<void> Collection::setProperties(const QVariantMap& properties)
    {
        auto label = properties.value(QStringLiteral(DBUS_INTERFACE_SECRET_COLLECTION ".Label")).toString();

        auto ret = setLabel(label);
        if (ret.isError()) {
            return ret;
        }

        return {};
    }

    const QSet<QString> Collection::aliases() const
    {
        return m_aliases;
    }

    DBusReturn<void> Collection::addAlias(QString alias)
    {
        auto ret = ensureBackend();
        if (ret.isError()) {
            return ret;
        }

        alias = encodePath(alias);

        if (m_aliases.contains(alias)) {
            return {};
        }

        emit aliasAboutToAdd(alias);

        bool ok = QDBusConnection::sessionBus().registerObject(
            QStringLiteral(DBUS_PATH_TEMPLATE_ALIAS).arg(p()->objectPath().path(), alias), this);
        if (ok) {
            m_aliases.insert(alias);
            emit aliasAdded(alias);
        }

        return {};
    }

    DBusReturn<void> Collection::removeAlias(QString alias)
    {
        auto ret = ensureBackend();
        if (ret.isError()) {
            return ret;
        }

        alias = encodePath(alias);

        if (!m_aliases.contains(alias)) {
            return {};
        }

        QDBusConnection::sessionBus().unregisterObject(
            QStringLiteral(DBUS_PATH_TEMPLATE_ALIAS).arg(p()->objectPath().path(), alias));

        m_aliases.remove(alias);
        emit aliasRemoved(alias);

        return {};
    }

    QString Collection::name() const
    {
        return QFileInfo(m_backendPath).baseName();
    }

    DatabaseWidget* Collection::backend() const
    {
        return m_backend;
    }

    void Collection::onDatabaseLockChanged()
    {
        auto locked = backendLocked();
        if (!locked) {
            populateContents();
        } else {
            cleanupConnections();
        }
        emit collectionLockChanged(locked);
        emit collectionChanged();
    }

    void Collection::populateContents()
    {
        if (!m_registered) {
            return;
        }

        // we have an unlocked db

        auto newUuid = FdoSecrets::settings()->exposedGroup(m_backend->database());
        auto newGroup = m_backend->database()->rootGroup()->findGroupByUuid(newUuid);
        if (!newGroup) {
            // no exposed group, delete self
            doDelete();
            return;
        }

        // clean up old group connections
        cleanupConnections();

        m_exposedGroup = newGroup;

        // Attach signal to update exposed group settings if the group was removed.
        // The lifetime of the connection is bound to the database object, because
        // in Database::~Database, groups are also deleted, but we don't want to
        // trigger this.
        // This rely on the fact that QObject disconnects signals BEFORE deleting
        // children.
        QPointer<Database> db = m_backend->database().data();
        connect(m_exposedGroup.data(), &Group::groupAboutToRemove, db, [db](Group* toBeRemoved) {
            if (!db) {
                return;
            }
            auto uuid = FdoSecrets::settings()->exposedGroup(db);
            auto exposedGroup = db->rootGroup()->findGroupByUuid(uuid);
            if (toBeRemoved == exposedGroup) {
                // reset the exposed group to none
                FdoSecrets::settings()->setExposedGroup(db, {});
            }
        });

        // Monitor exposed group settings
        connect(m_backend->database()->metadata()->customData(), &CustomData::customDataModified, this, [this]() {
            if (!m_exposedGroup || !m_backend) {
                return;
            }
            if (m_exposedGroup->uuid() == FdoSecrets::settings()->exposedGroup(m_backend->database())) {
                // no change
                return;
            }
            onDatabaseExposedGroupChanged();
        });

        // Add items for existing entry
        const auto entries = m_exposedGroup->entriesRecursive(false);
        for (const auto& entry : entries) {
            onEntryAdded(entry, false);
        }

        connectGroupSignalRecursive(m_exposedGroup);
    }

    void Collection::onDatabaseExposedGroupChanged()
    {
        // delete all items
        // this has to be done because the backend is actually still there
        // just we don't expose them
        for (const auto& item : asConst(m_items)) {
            item->doDelete();
        }

        // repopulate
        Q_ASSERT(!backendLocked());
        populateContents();
    }

    void Collection::onEntryAdded(Entry* entry, bool emitSignal)
    {
        if (inRecycleBin(entry)) {
            return;
        }

        auto item = new Item(this, entry);
        m_items << item;
        m_entryToItem[entry] = item;

        // forward delete signals
        connect(entry->group(), &Group::entryAboutToRemove, item, [item](Entry* toBeRemoved) {
            if (item->backend() == toBeRemoved) {
                item->doDelete();
            }
        });

        // relay signals
        connect(item, &Item::itemChanged, this, [this, item]() { emit itemChanged(item); });
        connect(item, &Item::itemAboutToDelete, this, [this, item]() {
            m_items.removeAll(item);
            m_entryToItem.remove(item->backend());
            emit itemDeleted(item);
        });

        if (emitSignal) {
            emit itemCreated(item);
        }
    }

    void Collection::connectGroupSignalRecursive(Group* group)
    {
        if (inRecycleBin(group)) {
            return;
        }

        connect(group, &Group::groupModified, this, &Collection::collectionChanged);
        connect(group, &Group::entryAdded, this, [this](Entry* entry) { onEntryAdded(entry, true); });

        const auto children = group->children();
        for (const auto& cg : children) {
            connectGroupSignalRecursive(cg);
        }
    }

    Service* Collection::service() const
    {
        return qobject_cast<Service*>(parent());
    }

    void Collection::doLock()
    {
        Q_ASSERT(m_backend);

        m_backend->lock();
    }

    void Collection::doUnlock()
    {
        Q_ASSERT(m_backend);

        service()->doUnlockDatabaseInDialog(m_backend);
    }

    void Collection::doDelete()
    {
        emit collectionAboutToDelete();

        unregisterCurrentPath();

        // remove alias manually to trigger signal
        for (const auto& a : aliases()) {
            removeAlias(a).okOrDie();
        }

        cleanupConnections();

        m_exposedGroup = nullptr;

        // reset backend and delete self
        m_backend = nullptr;
        deleteLater();
    }

    void Collection::cleanupConnections()
    {
        if (m_exposedGroup) {
            m_exposedGroup->disconnect(this);
        }
        m_items.clear();
    }

    QString Collection::backendFilePath() const
    {
        return m_backendPath;
    }

    Group* Collection::exposedRootGroup() const
    {
        return m_exposedGroup;
    }

    bool Collection::backendLocked() const
    {
        return !m_backend || !m_backend->database()->isInitialized() || m_backend->isLocked();
    }

    void Collection::doDeleteEntries(QList<Entry*> entries)
    {
        m_backend->deleteEntries(std::move(entries));
    }

    Group* Collection::findCreateGroupByPath(const QString& groupPath)
    {
        auto group = m_exposedGroup->findGroupByPath(groupPath);
        if (group) {
            return group;
        }

        // groupPath can't be empty here, because otherwise it will match m_exposedGroup and was returned above
        Q_ASSERT(!groupPath.isEmpty());

        auto groups = groupPath.split('/', QString::SkipEmptyParts);
        auto groupName = groups.takeLast();

        // create parent group
        auto parentGroup = findCreateGroupByPath(groups.join('/'));

        // create this group
        group = new Group();
        group->setUuid(QUuid::createUuid());
        group->setName(groupName);
        group->setIcon(Group::DefaultIconNumber);
        group->setParent(parentGroup);

        return group;
    }

    bool Collection::inRecycleBin(Group* group) const
    {
        Q_ASSERT(m_backend);

        if (!m_backend->database()->metadata()->recycleBin()) {
            return false;
        }

        while (group) {
            if (group->uuid() == m_backend->database()->metadata()->recycleBin()->uuid()) {
                return true;
            }
            group = group->parentGroup();
        }
        return false;
    }

    bool Collection::inRecycleBin(Entry* entry) const
    {
        Q_ASSERT(entry);
        return inRecycleBin(entry->group());
    }

} // namespace FdoSecrets