Пример #1
0
/**
 * Load library or several libraries from an external file. Return
 * pointer to the last new imported library.
 */
FWObject* ProjectPanel::loadLibrary(const string &libfpath)
{
    MessageBoxUpgradePredicate upgrade_predicate(mainW);
    FWObject *last_new_lib = nullptr;

    try
    {
        FWObjectDatabase *ndb = new FWObjectDatabase();
        ndb->load(libfpath,  &upgrade_predicate,  Constants::getDTDDirectory());

        FWObject *dobj = ndb->findInIndex(FWObjectDatabase::DELETED_OBJECTS_ID);
        if (dobj) ndb->remove(dobj, false);

        set<int> duplicate_ids;
        db()->findDuplicateIds(ndb, duplicate_ids);

        map<int, int> id_mapping;
        for (set<int>::iterator it=duplicate_ids.begin(); it!=duplicate_ids.end();
             ++it)
        {
            FWObject *obj = ndb->findInIndex(*it);
            assert(obj!=nullptr);
            int new_id = FWObjectDatabase::generateUniqueId();
            obj->setId(new_id);
            id_mapping[*it] = new_id;

            // cerr << "Duplicate ID: " << *it 
            //      << " " << FWObjectDatabase::getStringId(*it)
            //      << obj->getPath()
            //      << endl;
        }
        ndb->fixReferences(ndb, id_mapping);

        int new_lib_id = -1;

        // check for duplicate library names
        FWObjectTypedChildIterator it2 = ndb->findByType(Library::TYPENAME);
        for (; it2!=it2.end(); ++it2)
        {
            QString new_name = m_panel->om->makeNameUnique(
                db(), QString::fromUtf8((*it2)->getName().c_str()), Library::TYPENAME);
            (*it2)->setName(string(new_name.toUtf8()));
            if ((*it2)->getId() != FWObjectDatabase::STANDARD_LIB_ID)
                new_lib_id = (*it2)->getId();
        }

        MergeConflictRes mcr(this);
        db()->merge(ndb, &mcr);
        delete ndb;

        last_new_lib = db()->findInIndex(new_lib_id);
    } catch(FWException &ex)
    {
        QString error_txt = ex.toString().c_str();
        if (error_txt.length() > LONG_ERROR_CUTOFF) 
        {
            error_txt.truncate(LONG_ERROR_CUTOFF);
            error_txt += "\n\n" + tr("(Long error message was truncated)");
        }
        QMessageBox::critical(
            this,"Firewall Builder",
            tr("The program encountered error trying to load file %1.\n"
               "The file has not been loaded. Error:\n%2").
                 arg(libfpath.c_str()).arg(error_txt),
            tr("&Continue"), QString::null,QString::null,
            0, 1 );
    }
    return last_new_lib;
}
Пример #2
0
bool ProjectPanel::loadFromRCS(RCS *_rcs)
{
    resetFD();

    editingStandardLib = false;
    editingTemplateLib = false;

    bool forceSave=false; // use this flag to force 'save' operation if file should be renamed

    MessageBoxUpgradePredicate upgrade_predicate(mainW);

    assert(_rcs!=nullptr);

    rcs = _rcs;
    try
    {
        /* load the data file */
        systemFile = false;

        clearObjects();

        if (objdb)
        {
            objdb->destroyChildren();
            delete objdb;
        }

        objdb = new FWObjectDatabase();

// need to drop read-only flag on the database before I load new objects
        objdb->setReadOnly( false );

// always loading system objects
        mw->showStatusBarMessage(tr("Loading system objects...") );

        objdb->load( Constants::getStandardObjectsFilePath(),
                     &upgrade_predicate, Constants::getDTDDirectory());
        objdb->setFileName("");

// objects from a data file are in database ndb

        mw->showStatusBarMessage(tr("Reading and parsing data file..."));

        FWObjectDatabase *ndb = new FWObjectDatabase();
        ndb->load(rcs->getFileName().toLocal8Bit().constData(),
                  &upgrade_predicate,Constants::getDTDDirectory());
        time_t   oldtimestamp = ndb->getTimeLastModified();

/* loadingLib is true if user wants to open a library or master library file */
        bool loadingLib = editingLibrary();

        if (fwbdebug)
        {
            list<FWObject*> ll = ndb->getByType(Library::TYPENAME);
            for (FWObject::iterator i=ll.begin(); i!=ll.end(); i++)
            {
                qDebug("* Found library %s %s in the data file",
                       FWObjectDatabase::getStringId((*i)->getId()).c_str(),
                       (*i)->getName().c_str() );
            }
        }

/* if user opens library file, clear read-only flag so they can edit it */
        if (loadingLib)
        {
            list<FWObject*> ll = ndb->getByType(Library::TYPENAME);
            for (FWObject::iterator i=ll.begin(); i!=ll.end(); i++)
            {
                if ((*i)->getId()==FWObjectDatabase::STANDARD_LIB_ID)
                    editingStandardLib=true;
                if ((*i)->getId()==FWObjectDatabase::TEMPLATE_LIB_ID)
                    editingTemplateLib=true;
                (*i)->setReadOnly( false );
            }
        }

        mw->showStatusBarMessage(tr("Merging with system objects...") );

        MergeConflictRes mcr(mainW);
        objdb->merge(ndb, &mcr);

        ndb->destroyChildren();
        delete ndb;

        objdb->setFileName(rcs->getFileName().toLocal8Bit().constData());
        objdb->resetTimeLastModified(oldtimestamp);
        objdb->setDirty(false);

        if (fwbdebug)
        {
            qDebug("* Merge is done");
            list<FWObject*> ll = db()->getByType(Library::TYPENAME);
            for (FWObject::iterator i=ll.begin(); i!=ll.end(); i++)
            {
                qDebug("* Library %s %s in the data file",
                       FWObjectDatabase::getStringId((*i)->getId()).c_str(),
                       (*i)->getName().c_str() );
            }
        }


        /* this is a hack: 'Standard' library should be read-only. I
         * have too many files I already converted to the new API/DTD
         * and I am too lazy to convert them again, so I patch it up
         * here.
         *
         * However, if I am editing standard library, it should not be
         * read-only.
         */
        FWObject *slib = objdb->findInIndex(FWObjectDatabase::STANDARD_LIB_ID);
        if (slib!=nullptr )
        {
            if (fwbdebug)
                qDebug("standard library read-only status: %d, "
                       "editingStandardLib: %d",
                       slib->isReadOnly(), editingStandardLib);

            slib->setReadOnly(! editingStandardLib);
        }

        /* if the file name has an old extension .xml, change it to .fwb and
         * warn the user
         */
        QString fn = rcs->getFileName();
        QFileInfo ofinfo(fn);

        if ( ofinfo.suffix()=="xml")
        {
            if (fwbdebug)
            {
                qDebug("Need to rename file:  %s",
                       fn.toLatin1().constData());
                qDebug("             dirPath: %s",
                       ofinfo.dir().absolutePath().toLatin1().constData());
                qDebug("            filePath: %s",
                       ofinfo.absoluteFilePath().toLatin1().constData());
            }
            QString newFileName = ofinfo.dir().absolutePath()
                + "/" + ofinfo.completeBaseName() + ".fwb";
            
            bool needToRename = true;

            /* need these dances with symlinks to fix bug #1008956:
             * "Existing .fwb file gets overwritten if has wrong
             * extension"
             */
            QFileInfo nfinfo(newFileName);
            if (nfinfo.exists() && ofinfo.isSymLink() && ofinfo.readLink()==newFileName)
            {
                // .xml file is a symlink pointing at .fwb file
                // no need to rename
                needToRename = false;
            }

            if (needToRename)
            {
                if (nfinfo.exists())
                {
                    /* .fwb file exists but .xml is not a symlink
                     * .fwb is a separate file with the same name.
                     *
                     * tell the user we need to rename old file but
                     * the new file exists, then ask them to choose a
                     * new name. If the user chooses the same name and
                     * agrees to overwrite the file, just use this
                     * name. If the user hits cancel, tell them they
                     * need to choose a new name and open "file save"
                     * dialog again.
                     *
                     * Show the first dialog only once. If user hits
                     * Cancel, they see shorted version of the dialog
                     * and will be presented with "save file" dialog
                     * again.
                     */
                    QMessageBox::warning(
                        this,"Firewall Builder",
                        tr("Firewall Builder uses file extension '.fwb' and\n"
                           "needs to rename old data file '%1' to '%2',\n"
                           "but file '%3' already exists.\n"
                           "Choose a different name for the new file.")
                        .arg(fn).arg(newFileName).arg(newFileName),
                        tr("&Continue"), QString::null,QString::null,
                        0, 1 );

                    newFileName = chooseNewFileName(
                        fn, tr("Choose name and location for the new file"));
                    if (newFileName.isEmpty())
                    {
                        QString oldFileName = ofinfo.absoluteFilePath()
                            + ".bak";
                        rename(oldFileName.toLocal8Bit().constData(),
                               fn.toLocal8Bit().constData());

                        QMessageBox::warning(
                            this,"Firewall Builder",
                            tr("Load operation cancelled and data file reverted"
                               "to original version."),
                            tr("&Continue"), QString::null,QString::null,
                            0, 1 );

                        loadStandardObjects();
                        return false;
                    }
                    nfinfo.setFile(newFileName);
                }

                rename(fn.toLocal8Bit().constData(),
                       newFileName.toLocal8Bit().constData());

                QMessageBox::warning(
                this,"Firewall Builder",
                tr("Firewall Builder uses file extension '.fwb'. Your data"
                   "file '%1' \nhas been renamed '%2'")
                .arg(fn).arg(newFileName),
                tr("&Continue"), QString::null,QString::null,
                0, 1 );
            }

            fn = newFileName;
        }

        rcs->setFileName(fn);
        db()->setFileName(fn.toLocal8Bit().constData());

        //setWindowTitle(getPageTitle());
        //QCoreApplication::postEvent(mw, new updateSubWindowTitlesEvent());

        mainW->disableActions(m_panel->ruleSets->count()!=0);

        time_t last_modified = db()->getTimeLastModified();
        if (fwbdebug)
            qDebug("ProjectPanel::load(): load complete dirty=%d "
                   "last_modified=%s",
                   db()->isDirty(), ctime(&last_modified));
        
    } catch(FWException &ex)
    {
        QString trans = ex.getProperties()["failed_transformation"].c_str();
        QString elem  = ex.getProperties()["failed_element"].c_str();

        if(!trans.isEmpty() || !elem.isEmpty())
        {
            QString msg = tr("Exception: %1").arg(ex.toString().c_str());
            if (!trans.isEmpty())
            {
                trans.truncate(LONG_ERROR_CUTOFF);
                msg+="\n"+tr("Failed transformation : %1").arg(trans);
            }
            if (!elem.isEmpty())
            {
                elem.truncate(LONG_ERROR_CUTOFF);
                msg+="\n"+tr("XML element : %1").arg(elem);
            }
            QMessageBox::critical(
                this,"Firewall Builder",
                tr("The program encountered error trying to load data file.\n"
                   "The file has not been loaded. Error:\n%1").arg(msg),
                tr("&Continue"), QString::null,QString::null,
                0, 1 );
        } else
        {
            // this was not XML error, perhaps permissions or other
            // filesystem problem

            QString error_txt = QString::fromUtf8(ex.toString().c_str());
            if (error_txt.length() > LONG_ERROR_CUTOFF) 
            {
                error_txt.truncate(LONG_ERROR_CUTOFF);
                error_txt += "\n\n" + tr("(Long error message was truncated)");
            }

            QMessageBox::critical(
                this,"Firewall Builder",
                tr("The program encountered error trying to load data file.\n"
                   "The file has not been loaded. Error:\n%1").arg(
                       error_txt),
                tr("&Continue"), QString::null,QString::null,
                0, 1 );
        }
        // load standard objects so the window does not remain empty
        loadStandardObjects();
        return false;
    }

    db()->setReadOnly( rcs->isRO() || rcs->isTemp() );

// clear dirty flag for all objects, recursively
    if (!forceSave)  db()->setDirty(false);

    mw->showStatusBarMessage(tr("Building object tree..."));
    QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents, 100);

    loadObjects();
    QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents, 100);

    mw->showStatusBarMessage(tr("Indexing...") );
    db()->reIndex();

    setupAutoSave();

    time_t last_modified = db()->getTimeLastModified();
    if (fwbdebug)
        qDebug("ProjectPanel::load(): all done: "
               "dirty=%d last_modified=%s",
               db()->isDirty(), ctime(&last_modified));

    return true;
}