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;
}
Beispiel #2
0
int main(int argc, char **argv)
{   
    QCoreApplication app(argc, argv, false);

    // compilers always write file names into manifest in Utf8
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
    QTextCodec::setCodecForCStrings(QTextCodec::codecForName("Utf8"));
#endif
    QTextCodec::setCodecForLocale(QTextCodec::codecForName("Utf8"));
    
    QStringList args = app.arguments();

    if (args.size()<=1)
    {
        usage(argv[0]);
        exit(1);
    }

    QString last_arg;
    string filename;

    for (int idx=0; idx < args.size(); idx++)
    {
        QString arg = args.at(idx);
        last_arg = arg;
        if (arg == "-V")
        {
            usage(argv[0]);
            exit(0);
        }
        if (arg == "-f")
        {
            idx++;
            filename = string(args.at(idx).toLatin1().constData());
            continue;
        }
    }

    if (filename.empty())
    {
        usage(argv[0]);
        exit(1);
    }

    init(argv);

    try
    {
        new Resources(Constants::getResourcesFilePath());
 
        /* create database */
        objdb = new FWObjectDatabase();

        /* load the data file */
        UpgradePredicate upgrade_predicate; 

        cout << " *** Loading data ...";

        objdb->setReadOnly( false );
        objdb->load( filename, &upgrade_predicate, Constants::getDTDDirectory());
        objdb->setFileName(filename);
        objdb->reIndex();

        cout << " done\n";

        FWObject *slib = objdb->getById(FWObjectDatabase::STANDARD_LIB_ID);
        if (slib && slib->isReadOnly()) slib->setReadOnly(false);

        CompilerDriver_nxosacl *driver = new CompilerDriver_nxosacl(objdb);
        if (!driver->prepare(args))
        {
            usage(argv[0]);
            exit(1);
        }

        driver->compile();
        //int ret = (driver->getStatus() == BaseCompiler::FWCOMPILER_SUCCESS) ? 0 : 1;
        int ret = driver->getStatus();

        delete driver;
        delete objdb;

        return ret;
        
    } catch(libfwbuilder::FWException &ex)
    {
        cerr << ex.toString() << endl;
        return 1;
    } catch (std::string s)
    {
        cerr << s << endl;
        return 1;
    } catch (std::exception ex)
    {
        cerr << "exception: " << ex.what() << endl;
        return 1;
    } catch (...)
    {
        cerr << "Unsupported exception";
        return 1;
    }

    return 0;
}
void ObjectManipulator::deleteObject(FWObject *obj, QUndoCommand* macro)
{
    bool firstAction = true ;

    if (fwbdebug)
        qDebug() << "ObjectManipulator::deleteObject"
                 << "obj=" << obj
                 << "name=" << obj->getName().c_str();

    FWObject *object_library = obj->getLibrary();
    FWObject *parent = obj->getParent();
    FWObject *deleted_objects_lib = m_project->db()->findInIndex(
        FWObjectDatabase::DELETED_OBJECTS_ID );

    if (deleted_objects_lib == NULL)
    {
        FWObject *dobj = m_project->db()->createLibrary();
        dobj->setId(FWObjectDatabase::DELETED_OBJECTS_ID);
        dobj->setName("Deleted Objects");
        dobj->setReadOnly(false);
        m_project->db()->add(dobj);
        deleted_objects_lib = dobj;
    }

    if (object_library->getId() == FWObjectDatabase::STANDARD_LIB_ID)
        return;

    if (obj->isReadOnly()) return;

    if (obj->getId() == FWObjectDatabase::STANDARD_LIB_ID ||
        obj->getId() == FWObjectDatabase::DELETED_OBJECTS_ID) return;
    
    bool is_library = Library::isA(obj);
    bool is_firewall = Firewall::cast(obj) != NULL; // includes Cluster too
    bool is_deleted_object = (deleted_objects_lib!=NULL && obj->isChildOf(deleted_objects_lib));

    // ruleset_visible == true if 1) we delete firewall object and one of its
    // rulesets is visible in the project panel, or 2) we delete ruleset object
    // which is visible in the project panel
    bool ruleset_visible = (
        (is_firewall && m_project->getCurrentRuleSet()->isChildOf(obj)) ||
        (m_project->getCurrentRuleSet() == obj));

    mw->findObjectWidget->reset();

    QCoreApplication::postEvent(
        mw, new closeObjectEvent(m_project->getFileName(), obj->getId()));

#if 0
    // Remove object we are about to delete from the clipboard.
    // Sequence "delete then paste" is risky if the object is pasted into
    // a group or rule where only reference is added
    FWObjectClipboard::obj_clipboard->remove(obj);
#endif
 
    try
    {    
        if (fwbdebug)
            qDebug() << "ObjectManipulator::deleteObject"
                     << "is_library=" << is_library
                     << "is_firewall= " << is_firewall
                     << "ruleset_visible=" << ruleset_visible
                     << "is_deleted_object="<< is_deleted_object;

        if (is_deleted_object)
        {
            unselect();
            FWCmdDeleteObject *cmd = new FWCmdDeleteObject(
                m_project,
                obj,
                QString("Delete object"),
                macro);
            if (macro==0)
                m_project->undoStack->push(cmd);
            return;
        }

        if (is_library && obj->isReadOnly()) obj->setReadOnly(false);

        if (is_library) parent = m_project->db()->getFirstByType(Library::TYPENAME);

        actuallyDeleteObject(obj, macro);
        
        if (ruleset_visible) m_project->closeRuleSetPanel();
    }
    catch (FWException &ex)
    {
        if (fwbdebug)
            qDebug() << "ObjectManipulator::deleteObject:"
                     << "catch:  restoreOverrideCursor";
        QApplication::restoreOverrideCursor();
        QMessageBox::warning(
            this,"Firewall Builder",
            ex.toString().c_str(),
            "&Continue", QString::null,QString::null,
            0, 1 );
        throw(ex);
    }

    if (fwbdebug) qDebug("ObjectManipulator::deleteObject  done");

    firstAction = false ;
}