akabeibackend.cpp 19.4 KB
Newer Older
Dario Freddi's avatar
Dario Freddi committed
1 2 3 4 5 6 7 8 9 10
/* This file is part of the Chakra project

   Copyright (C) 2010 Dario Freddi <drf@chakra-project.org>

   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 of the License, or (at your option) any later version.
*/

11
#include "akabeibackend_p.h"
12

13 14
#include "akabeiconfig.h"
#include "akabeidatabase.h"
15
#include "akabeigroup.h"
16
#include "akabeipackage_p.h"
17
#include "akabeihelpers_p.h"
18
#include "akabeidelta_p.h"
19

20 21
#include <QtCore/QHash>
#include <QtCore/QtConcurrentRun>
22 23 24 25
#include <QtCore/QtConcurrentMap>
#include <QtCore/QDir>
#include <QtCore/QFutureWatcher>
#include <QVariant>
26

27 28 29
#include <archive.h>
#include <archive_entry.h>

Dario Freddi's avatar
Dario Freddi committed
30 31 32 33
Q_DECLARE_METATYPE(QUuid)
Q_DECLARE_METATYPE(QList< Akabei::Package* >)
Q_DECLARE_METATYPE(QList< Akabei::Group* >)

34 35 36
namespace Akabei
{

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
// For concurrent queries
struct ConcurrentPackageQuery
{
    ConcurrentPackageQuery(const QString &sql)
    : m_sql(sql) { }

    typedef QList< Package* > result_type;

    QList< Package* > operator()(Database *db)
    {
        return db->queryPackages(m_sql);
    }

    QString m_sql;
};

struct ConcurrentGroupQuery
{
    ConcurrentGroupQuery(const QString &sql)
    : m_sql(sql) { }

    typedef QList< Group* > result_type;

    QList< Group* > operator()(Database *db)
    {
        return db->queryGroups(m_sql);
    }

    QString m_sql;
};

68
QHash<QString, Database*> BackendPrivate::performInitialization()
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
    QHash<QString, Database*> rethash;

    // Check for the existence of all the needed directories
    QDir dbDir(Config::instance()->databasePath());
    if (!dbDir.exists()) {
        // Fail
        return QHash<QString, Database*>();
    }

    QDir cacheDir(Config::instance()->cachePath());
    if (!cacheDir.exists()) {
        // Fail
        return QHash<QString, Database*>();
    }

    QDir rootDir(Config::instance()->root());
    if (!rootDir.exists()) {
        // Fail
        return QHash<QString, Database*>();
    }

    // Initialize all databases. Local DB first.
    if (!QFile::exists(dbDir.absoluteFilePath("local.db"))) {
        // Fail
        return QHash<QString, Database*>();
    }

    Database *localDb = new Database(dbDir.absoluteFilePath("local.db"));
    if (!localDb->isValid()) {
        // Fail
        return QHash<QString, Database*>();
    }

    // Ok, add it to our rethash
    rethash.insert("local", localDb);

    // Now process all the various databases
    foreach (const QString &db, Config::instance()->databases()) {
        if (!QFile::exists(dbDir.absoluteFilePath(db + ".db"))) {
            // Fail, but just continue
            // TODO, maybe add a warning here
            continue;
        }

        Database *database = new Database(dbDir.absoluteFilePath(db + ".db"));
        if (!database->isValid()) {
            // Fail, but just continue
            // TODO, maybe add a warning here
            delete database;
            continue;
        }

        // Ok, add it to our rethash
        rethash.insert(db, database);
    }

    // Return it straight
    return rethash;
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

void BackendPrivate::setStatus(Backend::Status s)
{
    Q_Q(Backend);

    if (s != status) {
        status = s;
        emit q->statusChanged(status);
    }
}

void BackendPrivate::__k__initializationFinished()
{
    databases.clear();
    localDatabase = 0;

    // Let's see what we got
    QHash< QString, Database* > rethash = initializationWatcher->result();

    // Delete the watcher
    initializationWatcher->deleteLater();

    if (rethash.isEmpty()) {
        // Broken
        setStatus(Akabei::Backend::StatusBroken);
        return;
    }

    localDatabase = rethash["local"];
    if (!localDatabase) {
        // Something very wrong here
        setStatus(Akabei::Backend::StatusBroken);
        return;
    }

    // All the rest
    for (QHash< QString, Database* >::const_iterator i = rethash.constBegin(); i != rethash.constEnd(); ++i) {
        if (i.key() == "local") {
            // Skip
            continue;
        }

        databases.append(i.value());
    }

    // The backend is now ready
    setStatus(Akabei::Backend::StatusReady);
}

178 179 180 181 182 183 184 185
void BackendPrivate::packageQueryFinished()
{
    Q_Q(Backend);

    QUuid uuid = QUuid(sender()->property("__Akabei_Query_Uuid").toString());
    if (!queryPackageFuturePool.contains(uuid)) {
        qWarning() << "No such UUID registered!";
        emit q->queryPackagesCompleted(uuid, QList<Package*>());
Dario Freddi's avatar
Dario Freddi committed
186
        sender()->deleteLater();
187 188 189 190 191 192 193 194 195 196
        return;
    }

    QList<Package*> retlist;
    // Create the result
    QFuture< QList< Package* > > future = queryPackageFuturePool[uuid]->future();
    for (QFuture< QList< Package* > >::const_iterator i = future.constBegin(); i != future.constEnd(); ++i) {
        retlist << *i;
    }

Dario Freddi's avatar
Dario Freddi committed
197
    sender()->deleteLater();
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
    emit q->queryPackagesCompleted(uuid, retlist);
}

void BackendPrivate::groupQueryFinished()
{
    Q_Q(Backend);

    QUuid uuid = QUuid(sender()->property("__Akabei_Query_Uuid").toString());
    if (!queryGroupFuturePool.contains(uuid)) {
        qWarning() << "No such UUID registered!";
        emit q->queryGroupCompleted(uuid, QList<Group*>());
        return;
    }

    QList<Group*> retlist;
    // Create the result
    QFuture< QList< Group* > > future = queryGroupFuturePool[uuid]->future();
    for (QFuture< QList< Group* > >::const_iterator i = future.constBegin(); i != future.constEnd(); ++i) {
        retlist << *i;
    }

    emit q->queryGroupCompleted(uuid, retlist);
}

///////////////////////////

GroupPool::GroupPool()
{
}

GroupPool::~GroupPool()
{
}

Group *GroupPool::group(const QString &name)
{
    if (!m_pool.contains(name)) {
        m_pool.insert(name, new Group(name));
    }

    return m_pool[name];
}

bool GroupPool::contains(const QString &name)
{
    return m_pool.contains(name);
}

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
///////////////////////////

class BackendHelper
{
public:
    BackendHelper() : q(0) {}
    ~BackendHelper() {
        delete q;
    }
    Backend *q;
};

Q_GLOBAL_STATIC(BackendHelper, s_globalBackend)

Backend *Backend::instance()
{
    if (!s_globalBackend()->q) {
        new Backend;
    }

    return s_globalBackend()->q;
}

Backend::Backend(QObject* parent)
    : QObject(parent)
    , d_ptr(new BackendPrivate(this))
{
    Q_ASSERT(!s_globalBackend()->q);
    s_globalBackend()->q = this;
Dario Freddi's avatar
Dario Freddi committed
275 276 277
    qRegisterMetaType<QUuid>();
    qRegisterMetaType< QList< Akabei::Package* > >();
    qRegisterMetaType< QList< Akabei::Group* > >();
278 279 280 281 282 283

    // We need at least 2 threads in QThreadPool to make everything work correctly.
    if (QThreadPool::globalInstance()->maxThreadCount() < 2) {
        qDebug() << "Set max thread count to 2";
        QThreadPool::globalInstance()->setMaxThreadCount(2);
    }
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
}

Backend::~Backend()
{
}

void Backend::initialize()
{
    Q_D(Backend);

    d->setStatus(StatusInitializing);

    d->initializationWatcher = new QFutureWatcher< QHash< QString, Database* > >(this);
    connect(d->initializationWatcher, SIGNAL(finished()), this, SLOT(__k__initializationFinished()));

    QFuture< QHash< QString, Database* > > future = QtConcurrent::run(d, &BackendPrivate::performInitialization);
    d->initializationWatcher->setFuture(future);
}

QList< Database* > Backend::databases()
{
305 306
    Q_D(Backend);
    return d->databases;
307 308 309 310 311 312 313 314 315 316 317 318 319 320
}

Database* Backend::localDatabase()
{
    Q_D(Backend);
    return d->localDatabase;
}

Backend::Status Backend::status() const
{
    Q_D(const Backend);
    return d->status;
}

321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
QUuid Backend::groups()
{
    QString sql = "SELECT * FROM groups";
    return queryGroups(sql);
}

QUuid Backend::packages()
{
    QString sql = "SELECT * FROM packages";
    return queryPackages(sql);
}

QUuid Backend::queryGroups(const QString& sql)
{
    Q_D(Backend);

    QUuid uuid = QUuid::createUuid();

    QList<Database*> allDbs;
    allDbs << d->localDatabase << d->databases;

Dario Freddi's avatar
Dario Freddi committed
342
    QFutureWatcher< QList< Group* > > *watcher = new QFutureWatcher< QList< Group* > >();
343 344 345 346 347 348
    watcher->setProperty("__Akabei_Query_Uuid", uuid.toString());
    connect(watcher, SIGNAL(finished()), d, SLOT(groupQueryFinished()));
    d->queryGroupFuturePool.insert(uuid, watcher);

    QFuture< QList< Group* > > future = QtConcurrent::mapped(allDbs, ConcurrentGroupQuery(sql));
    watcher->setFuture(future);
349 350

    return uuid;
351 352 353 354 355 356 357 358 359 360 361
}

QUuid Backend::queryPackages(const QString& sql)
{
    Q_D(Backend);

    QUuid uuid = QUuid::createUuid();

    QList<Database*> allDbs;
    allDbs << d->localDatabase << d->databases;

Dario Freddi's avatar
Dario Freddi committed
362
    QFutureWatcher< QList< Package* > > *watcher = new QFutureWatcher< QList< Package* > >();
363 364 365 366 367 368
    watcher->setProperty("__Akabei_Query_Uuid", uuid.toString());
    connect(watcher, SIGNAL(finished()), d, SLOT(packageQueryFinished()));
    d->queryPackageFuturePool.insert(uuid, watcher);

    QFuture< QList< Package* > > future = QtConcurrent::mapped(allDbs, ConcurrentPackageQuery(sql));
    watcher->setFuture(future);
369 370

    return uuid;
371 372 373 374 375 376 377 378 379 380 381 382 383 384
}

QUuid Backend::searchGroups(const QString& token)
{
    QString sql = "SELECT * FROM groups WHERE Name LIKE \"%" + token + "%\" OR Description LIKE \"%" + token + "%\"";
    return queryGroups(sql);
}

QUuid Backend::searchPackages(const QString& token)
{
    QString sql = "SELECT * FROM packages WHERE Name LIKE \"%" + token + "%\" OR Description LIKE \"%" + token + "%\"";
    return queryPackages(sql);
}

385 386 387 388 389 390
OperationRunner* Backend::operationRunner()
{
    Q_D(Backend);
    return d->runner;
}

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
Package* Backend::loadPackageFromFile(const QString& path)
{
    Q_D(Backend);
    int ret = ARCHIVE_OK;
    struct archive *archive;
    struct archive_entry *entry;

    if (!QFile::exists(path)) {
        return 0;
    }

    if((archive = archive_read_new()) == NULL) {
//         RET_ERR(PM_ERR_LIBARCHIVE, NULL);
        return 0;
    }

    archive_read_support_compression_all(archive);
    archive_read_support_format_all(archive);

    if (archive_read_open_filename(archive, path.toUtf8().data(), ARCHIVE_DEFAULT_BYTES_PER_BLOCK) != ARCHIVE_OK) {
//         RET_ERR(PM_ERR_PKG_OPEN, NULL);
        return 0;
    }

    Package *retpackage = new Package;
416 417
    retpackage->d_func()->hasScriptlet = false;
    retpackage->d_func()->hasHooks = false;
418
    retpackage->d_func()->pathToArchive = path;
419 420 421 422 423 424 425 426

    /* If full is false, only read through the archive until we find our needed
     * metadata. If it is true, read through the entire archive, which serves
     * as a verfication of integrity and allows us to create the filelist. */
    while((ret = archive_read_next_header(archive, &entry)) == ARCHIVE_OK) {
        const char *entry_name = archive_entry_pathname(entry);

        if(strcmp(entry_name, ".PKGINFO") == 0) {
427 428
            // Go and read from the archive
            char fline[512];
429
            while (Helpers::archive_file_readline(archive, fline) != 0) {
430
                QString line(fline);
431 432 433 434 435 436

                if (!line.contains('=') || line.startsWith('#')) {
                    // Skip this line, not interesting
                    continue;
                }

437 438
                line.remove('\n');

439
                // Separate the two strings
Dario Freddi's avatar
Dario Freddi committed
440 441 442 443 444
                QStringList splitted = line.split('=');
                QString key = splitted.first();
                // There might be an equal, so
                splitted.removeAt(0);
                QString value = splitted.join(QChar('='));
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464

                // Just remove all spaces ignorantly here
                key = key.remove(' ');
                // Recheck if it's commented over
                if (key.startsWith('#')) {
                    // Pass by
                }

                // Strip whitespaces here instead
                while (value.startsWith(' ')) {
                    value = value.remove(0, 1);
                }
                while (value.endsWith(' ')) {
                    value = value.remove(value.length() - 1, 1);
                }

                // Ok, now let's analyze
                if (key == "pkgname") {
                    retpackage->d_func()->name = value;
                } else if (key == "pkgver") {
Dario Freddi's avatar
Dario Freddi committed
465
                    retpackage->d_func()->version = value.toUtf8();
466 467 468 469 470
                } else if (key == "pkgdesc") {
                    retpackage->d_func()->desc = value;
                } else if (key == "group") {
                    retpackage->d_func()->groups << d->groupPool->group(value);
                } else if (key == "url") {
471
                    retpackage->d_func()->url = QUrl(value);
472
                } else if (key == "license") {
473
                    retpackage->d_func()->license = value;
474 475 476 477 478 479 480 481
                } else if (key == "builddate") {
                    retpackage->d_func()->buildDate = QDateTime::fromTime_t(value.toUInt());
                } else if (key == "packager") {
                    retpackage->d_func()->packager = value;
                } else if (key == "arch") {
                    retpackage->d_func()->arch = value;
                } else if (key == "size") {
                    retpackage->d_func()->size = value.toInt();
Dario Freddi's avatar
Dario Freddi committed
482 483 484
                } else if (key == "depend") {
                    retpackage->d_func()->deps << value;
                } else if (key == "optdepend") {
485
                    retpackage->d_func()->optdepends << value;
Dario Freddi's avatar
Dario Freddi committed
486 487 488
                } else if (key == "conflict") {
                    retpackage->d_func()->conflicts << value;
                } else if (key == "replaces") {
489
                    retpackage->d_func()->replaces << value;
Dario Freddi's avatar
Dario Freddi committed
490 491 492
                } else if (key == "provides") {
                    retpackage->d_func()->providers << value;
                } else if (key == "backup") {
493
                    retpackage->d_func()->backup << value;
Dario Freddi's avatar
Dario Freddi committed
494 495 496
                } else if (key == "makepkgopt") {
//                     retpackage->d_func()->arch = value;
                } else if (key == "screeenshot") {
497
                    retpackage->d_func()->screenshot = QUrl(value);
Dario Freddi's avatar
Dario Freddi committed
498 499
                } else if (key == "mimetype") {
                    retpackage->d_func()->mimetypes << value;
500 501 502
                } else if (key == "hook") {
                    retpackage->d_func()->hooks << value;
                    retpackage->d_func()->hasHooks = true;
503 504 505 506
                }
            }
            continue;
        } else if(strcmp(entry_name,  ".INSTALL") == 0) {
507 508
            QString scriptlet;
            char fline[512];
509
            while (Helpers::archive_file_readline(archive, fline) != 0) {
510 511 512
                scriptlet.append(fline);
            }
            retpackage->d_func()->scriptlet = scriptlet;
513
            retpackage->d_func()->hasScriptlet = true;
514
            continue;
Dario Freddi's avatar
Dario Freddi committed
515 516 517 518 519 520 521
        } else if(*entry_name == '.') {
            /* for now, ignore all files starting with '.' that haven't
             * already been handled (for future possibilities) */
        } else {
            /* Keep track of all files for filelist generation */
            retpackage->d_func()->files << entry_name;
            retpackage->d_func()->isize += archive_entry_size(entry);
522 523
        }

524
        if (archive_read_data_skip(archive)) {
525
            delete retpackage;
526 527 528 529
            return 0;
        }
    }

530 531 532 533 534 535 536 537 538 539
    // Some checks
    if (ret != ARCHIVE_EOF) {
        delete retpackage;
        return 0;
    }
    if (retpackage->name().isEmpty()) {
        delete retpackage;
        return 0;
    }

540 541
    archive_read_finish(archive);

Dario Freddi's avatar
Dario Freddi committed
542 543
    // Now add md5sum and filename, of course
    retpackage->d_func()->filename = path.split('/').last();
544
    retpackage->d_func()->md5sum = Helpers::md5sumOfFile(path);
Dario Freddi's avatar
Dario Freddi committed
545

546 547 548 549
    // And size
    QFileInfo finfo(path);
    retpackage->d_func()->size = finfo.size();

550 551 552 553
    // Fill some fields
    retpackage->d_func()->installDate = QDateTime();
    retpackage->d_func()->reason = Package::NoReason;

554 555 556 557
    // We already computed md5 and validation, so set em up
    retpackage->d_func()->_p_md5checked = true;
    retpackage->d_func()->_p_validated = true;

558 559 560
    return retpackage;
}

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 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675
Delta* Backend::loadDeltaFromFile(const QString& path)
{
    int ret = ARCHIVE_OK;
    struct archive *archive;
    struct archive_entry *entry;

    if (!QFile::exists(path)) {
        return 0;
    }

    if((archive = archive_read_new()) == NULL) {
//         RET_ERR(PM_ERR_LIBARCHIVE, NULL);
        return 0;
    }

    archive_read_support_compression_all(archive);
    archive_read_support_format_all(archive);

    if (archive_read_open_filename(archive, path.toUtf8().data(), ARCHIVE_DEFAULT_BYTES_PER_BLOCK) != ARCHIVE_OK) {
//         RET_ERR(PM_ERR_PKG_OPEN, NULL);
        return 0;
    }

    Delta *retdelta = new Delta(QString(), QByteArray(), QByteArray());
    retdelta->d_func()->pathToDelta = path;

    /* If full is false, only read through the archive until we find our needed
     * metadata. If it is true, read through the entire archive, which serves
     * as a verfication of integrity and allows us to create the filelist. */
    while((ret = archive_read_next_header(archive, &entry)) == ARCHIVE_OK) {
        const char *entry_name = archive_entry_pathname(entry);

        if(strcmp(entry_name, ".DELTAINFO") == 0) {
            // Go and read from the archive
            char fline[512];
            while (Helpers::archive_file_readline(archive, fline) != 0) {
                QString line(fline);

                if (!line.contains('=') || line.startsWith('#')) {
                    // Skip this line, not interesting
                    continue;
                }

                line.remove('\n');

                // Separate the two strings
                QStringList splitted = line.split('=');
                QString key = splitted.first();
                // There might be an equal, so
                splitted.removeAt(0);
                QString value = splitted.join(QChar('='));

                // Just remove all spaces ignorantly here
                key = key.remove(' ');
                // Recheck if it's commented over
                if (key.startsWith('#')) {
                    // Pass by
                }

                // Strip whitespaces here instead
                while (value.startsWith(' ')) {
                    value = value.remove(0, 1);
                }
                while (value.endsWith(' ')) {
                    value = value.remove(value.length() - 1, 1);
                }

                // Ok, now let's analyze
                if (key == "pkgname") {
                    retdelta->d_func()->name = value;
                } else if (key == "verfrom") {
                    retdelta->d_func()->vFrom = value.toUtf8();
                } else if (key == "verto") {
                    retdelta->d_func()->vTo = value.toUtf8();
                }
            }
            continue;
        } else if(*entry_name == '.') {
            /* for now, ignore all files starting with '.' that haven't
             * already been handled (for future possibilities) */
        } else {
            // It can be only our delta
            if (entry_name != path.split('/').last().remove(".tar.xz")) {
                delete retdelta;
                return 0;
            }
        }

        if (archive_read_data_skip(archive)) {
            delete retdelta;
            return 0;
        }
    }

    // Some checks
    if (ret != ARCHIVE_EOF) {
        delete retdelta;
        return 0;
    }
    if (retdelta->targetName().isEmpty()) {
        delete retdelta;
        return 0;
    }

    // Now add md5sum and filename, of course
    retdelta->d_func()->filename = path.split('/').last();
    retdelta->d_func()->md5sum = Helpers::md5sumOfFile(path);

    // We already computed md5 and validation, so set em up
    retdelta->d_func()->_p_md5checked = true;
    retdelta->d_func()->_p_validated = true;

    return retdelta;
}

676 677 678
}

#include "akabeibackend.moc"