udisks2blockdevices.cpp 12.5 KB
Newer Older
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
/*
 * Copyright (C) 2018 Jolla Ltd. <raine.makelainen@jolla.com>
 *
 * You may use this file under the terms of the BSD license as follows:
 *
 * "Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in
 *     the documentation and/or other materials provided with the
 *     distribution.
 *   * Neither the name of Nemo Mobile nor the names of its contributors
 *     may be used to endorse or promote products derived from this
 *     software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
 */

#include "udisks2blockdevices_p.h"
#include "partitionmanager_p.h"
#include "logging_p.h"

#include <QRegularExpression>
#include <QTimerEvent>

#include <QDebug>

#define PARTITION_WAIT_TIMEOUT 3000

using namespace UDisks2;

45
QPointer<BlockDevices> BlockDevices::sharedInstance = nullptr;
46 47 48

BlockDevices *BlockDevices::instance()
{
49
    return sharedInstance ? sharedInstance.data() : new BlockDevices;
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
}

BlockDevices::~BlockDevices()
{
    qDeleteAll(m_blockDevices);
    qDeleteAll(m_partitionWaits);

    m_blockDevices.clear();
    m_partitionWaits.clear();
    sharedInstance = nullptr;
}

bool BlockDevices::contains(const QString &dbusObjectPath) const
{
    return m_blockDevices.contains(dbusObjectPath);
}

void BlockDevices::remove(const QString &dbusObjectPath)
{
69 70 71 72 73
    if (contains(dbusObjectPath)) {
        Block *block = m_blockDevices.take(dbusObjectPath);
        clearPartitionWait(dbusObjectPath, false);
        delete block;
    }
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
}

Block *BlockDevices::device(const QString &dbusObjectPath) const
{
    return m_blockDevices.value(dbusObjectPath, nullptr);
}

Block *BlockDevices::replace(const QString &dbusObjectPath, Block *block)
{
    Block *deviceReplace = device(dbusObjectPath);

    // Clear partition wait before morphing a block.
    if (m_partitionWaits.contains(deviceReplace->partitionTable())) {
        clearPartitionWait(deviceReplace->partitionTable(), false);
    }

    deviceReplace->morph(*block);
    m_blockDevices.remove(dbusObjectPath);
    insert(deviceReplace->path(), deviceReplace);
    block->deleteLater();
    return deviceReplace;
}

void BlockDevices::insert(const QString &dbusObjectPath, Block *block)
{
    m_blockDevices.insert(dbusObjectPath, block);
}

Block *BlockDevices::find(std::function<bool (const Block *)> condition)
{
    for (QMap<QString, Block *>::const_iterator i = m_blockDevices.constBegin(); i != m_blockDevices.constEnd(); ++i) {
        Block *block = i.value();
        if (condition(block)) {
            return block;
        }
    }
    return nullptr;
}

Block *BlockDevices::find(const QString &devicePath)
{
    return find([devicePath](const Block *block){
        return block->device() == devicePath || block->cryptoBackingDevicePath() == devicePath;
    });
}

QString BlockDevices::objectPath(const QString &devicePath) const
{
    for (QMap<QString, Block *>::const_iterator i = m_blockDevices.constBegin(); i != m_blockDevices.constEnd(); ++i) {
        Block *block = i.value();
        if (block->device() == devicePath) {
            return block->path();
        } else if (block->cryptoBackingDevicePath() == devicePath) {
            return block->cryptoBackingDeviceObjectPath();
        }
    }

    return QString();
}

QStringList BlockDevices::devicePaths(const QStringList &dbusObjectPaths) const
{
    QStringList paths;
    for (const QString &objectPath : dbusObjectPaths) {
        for (QMap<QString, Block *>::const_iterator i = m_blockDevices.constBegin(); i != m_blockDevices.constEnd(); ++i) {
            Block *block = i.value();
            if (block->path() == objectPath || block->cryptoBackingDeviceObjectPath() == objectPath) {
                paths << block->device();
            }
        }
    }
    return paths;
}

bool BlockDevices::createBlockDevice(const QString &dbusObjectPath, const InterfacePropertyMap &interfacePropertyMap)
{
    if (!BlockDevices::isExternal(dbusObjectPath)) {
151
        updatePopulatedCheck();
152 153 154 155 156 157
        return false;
    }

    return doCreateBlockDevice(dbusObjectPath, interfacePropertyMap);
}

158 159 160 161 162 163 164 165 166 167 168 169 170
void BlockDevices::createBlockDevices(const QList<QDBusObjectPath> &devices)
{
    m_blockCount = devices.count();
    if (m_blockCount == 0) {
        m_populated = true;
        emit externalStoragesPopulated();
    }

    for (const QDBusObjectPath &dbusObjectPath : devices) {
        createBlockDevice(dbusObjectPath.path(), UDisks2::InterfacePropertyMap());
    }
}

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
void BlockDevices::lock(const QString &dbusObjectPath)
{
    Block *deviceMapped = find([dbusObjectPath](const Block *block) {
        return block->cryptoBackingDeviceObjectPath() == dbusObjectPath;
    });

    if (deviceMapped && (deviceMapped->isLocking() || deviceMapped->isFormatting())) {
        Block *newBlock = doCreateBlockDevice(dbusObjectPath, InterfacePropertyMap());
        if (newBlock && deviceMapped->isFormatting()) {
            newBlock->setFormatting(true);
        }
    }
}

void BlockDevices::waitPartition(Block *block)
{
    m_partitionWaits.insert(block->path(), new PartitionWaiter(startTimer(PARTITION_WAIT_TIMEOUT), block));
}

void BlockDevices::clearPartitionWait(const QString &dbusObjectPath, bool destroyBlock)
{
    PartitionWaiter *waiter = m_partitionWaits.value(dbusObjectPath,  nullptr);
    if (waiter) {
        killTimer(waiter->timer);

        // Just nullify block and let it live.
        if (!destroyBlock) {
            waiter->block = nullptr;
        }

        delete waiter;
    }

    m_partitionWaits.remove(dbusObjectPath);
}

void BlockDevices::removeInterfaces(const QString &dbusObjectPath, const QStringList &interfaces)
{
209 210 211 212
    clearPartitionWait(dbusObjectPath, false);

    UDisks2::Block *block = device(dbusObjectPath);
    if (block) {
213 214 215 216 217 218
        if (interfaces.contains(UDISKS2_FILESYSTEM_INTERFACE)) {
            block->removeInterface(UDISKS2_FILESYSTEM_INTERFACE);
        }
        if (interfaces.contains(UDISKS2_ENCRYPTED_INTERFACE)) {
            block->removeInterface(UDISKS2_ENCRYPTED_INTERFACE);
        }
219 220 221 222 223

        if (interfaces.contains(UDISKS2_BLOCK_INTERFACE)) {
            delete block;
            m_blockDevices.remove(dbusObjectPath);
        }
224 225 226
    }
}

227 228 229 230 231
bool BlockDevices::populated() const
{
    return m_populated;
}

232 233 234 235 236 237 238 239 240
bool BlockDevices::isExternal(const QString &dbusObjectPath)
{
    static const QRegularExpression externalBlockDevice(QStringLiteral("^/org/freedesktop/UDisks2/block_devices/%1$").arg(externalDevice));
    return externalBlockDevice.match(dbusObjectPath).hasMatch();
}

void BlockDevices::blockCompleted()
{
    Block *completedBlock = qobject_cast<Block *>(sender());
241 242
    if (completedBlock->isValid() && (completedBlock->isPartitionTable() ||
                                      (completedBlock->hasInterface(UDISKS2_BLOCK_INTERFACE) && completedBlock->interfaceCount() == 1)) ){
243 244
        qCInfo(lcMemoryCardLog) << "Start waiting for block" << completedBlock->device();
        waitPartition(completedBlock);
245
        updatePopulatedCheck();
246 247 248 249 250
        return;
    }

    clearPartitionWait(completedBlock->partitionTable(), true);
    complete(completedBlock);
251 252 253

    // Check only after complete has been called.
    updatePopulatedCheck();
254 255 256 257
}

BlockDevices::BlockDevices(QObject *parent)
    : QObject(parent)
258 259
    , m_blockCount(0)
    , m_populated(false)
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
{
    Q_ASSERT(!sharedInstance);

    sharedInstance = this;
}

Block *BlockDevices::doCreateBlockDevice(const QString &dbusObjectPath, const InterfacePropertyMap &interfacePropertyMap)
{
    if (contains(dbusObjectPath)) {
        Block *block = device(dbusObjectPath);
        if (block && interfacePropertyMap.contains(UDISKS2_FILESYSTEM_INTERFACE)) {
            block->addInterface(UDISKS2_FILESYSTEM_INTERFACE, interfacePropertyMap.value(UDISKS2_FILESYSTEM_INTERFACE));
        }
        if (block && interfacePropertyMap.contains(UDISKS2_ENCRYPTED_INTERFACE)) {
            block->addInterface(UDISKS2_ENCRYPTED_INTERFACE, interfacePropertyMap.value(UDISKS2_ENCRYPTED_INTERFACE));
        }

        return block;
    }

    Block *block = new Block(dbusObjectPath, interfacePropertyMap);
    updateFormattingState(block);
    connect(block, &Block::completed, this, &BlockDevices::blockCompleted);
    return block;
}

void BlockDevices::updateFormattingState(Block *block)
{
    Block *cryptoBackingDevice = nullptr;
    QString cryptoBackingDevicePath = block->cryptoBackingDeviceObjectPath();

    // If we have crypto backing device, copy over formatting state.
    if (cryptoBackingDevicePath != QLatin1String("/") && (cryptoBackingDevice = m_blockDevices.value(cryptoBackingDevicePath, nullptr))) {
        block->blockSignals(true);
        block->setFormatting(cryptoBackingDevice->isFormatting());
        block->blockSignals(false);
    }
}

void BlockDevices::dumpBlocks() const
{
    for (QMap<QString, Block *>::const_iterator i = m_blockDevices.constBegin(); i != m_blockDevices.constEnd(); ++i) {
        i.value()->dumpInfo();
    }
}

void BlockDevices::complete(Block *block, bool forceAccept)
{
    if (!block->isExternal()) {
        block->deleteLater();
        return;
    }

    // Check if device is already unlocked.
    Block *unlocked = nullptr;
    if (block->isEncrypted()) {
        QString newPath = block->path();
        unlocked = find([newPath](const Block *block) {
318
            return block->cryptoBackingDeviceObjectPath() == newPath && !block->isLocking();
319 320 321
        });
    }

322
    bool willAccept = !unlocked && (block->isPartition() || block->isMountable() || block->isEncrypted() || block->isFormatting() || forceAccept);
323
    qCInfo(lcMemoryCardLog) << "Completed block" << qPrintable(block->path())
324
                            << "is" << (willAccept ? "accepted" : block->isPartition() ? "kept" : "rejected");
325 326 327
    block->dumpInfo();

    if (willAccept) {
328 329
        // Hope that somebody will handle this signal and call insert()
        // to add this block to m_blockDevices.
330
        emit newBlock(block);
331 332 333 334
    } else if (block->isPartition()) {
        // Silently keep partitions around so that we can filter out
        // partition tables in timerEvent().
        insert(block->path(), block);
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
    } else {
        // This is garbage block device that should not be exposed
        // from the partition model.
        block->removeInterface(UDISKS2_BLOCK_INTERFACE);
        block->deleteLater();
    }
}

void BlockDevices::timerEvent(QTimerEvent *e)
{
    for (QMap<QString, PartitionWaiter *>::iterator i = m_partitionWaits.begin(); i != m_partitionWaits.end(); ++i) {
        PartitionWaiter *waiter = i.value();
        int timerId = waiter->timer;
        if (e->timerId() == timerId) {
            QString path = i.key();
            qCDebug(lcMemoryCardLog) << "Waiting partitions:" << m_partitionWaits.keys() << path;
            dumpBlocks();

            Block *partitionTable = find([path](const Block *block) {
                return block->partitionTable() == path;
            });

            // No partition found that would be part of this partion table. Accept this one.
            if (!partitionTable) {
                complete(waiter->block, true);
            }
            clearPartitionWait(path, partitionTable);
            break;
        }
    }
}

367 368 369 370 371 372 373 374 375 376 377
void BlockDevices::updatePopulatedCheck()
{
    if (!m_populated) {
        --m_blockCount;
        if (m_blockCount == 0) {
            m_populated = true;
            emit externalStoragesPopulated();
        }
    }
}

378 379 380 381 382 383 384 385 386 387 388 389
BlockDevices::PartitionWaiter::PartitionWaiter(int timer, Block *block)
    : timer(timer)
    , block(block)
{
}

BlockDevices::PartitionWaiter::~PartitionWaiter()
{
    delete block;
    block = nullptr;
    timer = 0;
}