示例#1
0
///////////////////////////////////////////////////////////////////////////////
// IsObjectEncrypted
///////////////////////////////////////////////////////////////////////////////
bool cTWUtil::IsObjectEncrypted(const TCHAR* objFileName, const cFileHeaderID& fhid, const TSTRING& errorMsg)
{
    bool   fEncrypted = false;
    cDebug d("IsObjectEncrypted");
    d.TraceDebug(_T("Reading from file %s\n"), objFileName);

    try
    {
        cFileArchive arch;
        arch.OpenRead(objFileName);

        cFileHeader     fileHeader;
        cSerializerImpl fhSer(arch, cSerializerImpl::S_READ, objFileName);
        fileHeader.Read(&fhSer);

        // check for a mismatched header
        if (fileHeader.GetID() != fhid)
            ThrowAndAssert(eSerializerInputStreamFmt(_T(""), objFileName, eSerializer::TY_FILE));

        // switch on the type of encoding...
        if (fileHeader.GetEncoding() == cFileHeader::ASYM_ENCRYPTION)
        {
            fEncrypted = true;
        }
        else if (fileHeader.GetEncoding() == cFileHeader::COMPRESSED)
        {
            fEncrypted = false;
        }
        else
            // unknown encoding...
            ThrowAndAssert(eSerializerInputStreamFmt(_T(""), objFileName, eSerializer::TY_FILE));
    }
    catch (eArchive& e)
    {
        // Note: Output to TCERR is O.K. here, it is documented that this is what this function does
        TSTRING msg = e.GetMsg();
        if (!msg.empty())
            msg += _T("\n");
        msg += errorMsg;

        cTWUtil::PrintErrorMsg(ePoly(e.GetID(), msg, e.GetFlags()));
        ThrowAndAssert(ePoly());
    }
    catch (eSerializer& e)
    {
        // Note: Output to TCERR is O.K. here, it is documented that this is what this function does
        TSTRING msg = e.GetMsg();
        if (!msg.empty())
            msg += _T("\n");
        msg += errorMsg;

        cTWUtil::PrintErrorMsg(ePoly(e.GetID(), msg, e.GetFlags()));
        ThrowAndAssert(ePoly());
    }

    return (fEncrypted);
}
void cFCOPropUint64::Read(iSerializer* pSerializer, int32 version)
{
    if (version > 0)
        ThrowAndAssert(eSerializerVersionMismatch(_T("uint64 Property Read")));

    pSerializer->ReadInt64((int64&)mValue);
}
void cFCOPropTSTRING::Read(iSerializer* pSerializer, int32 version)
{
    if (version > 0)
        ThrowAndAssert(eSerializerVersionMismatch(_T("String Property Read")));

    pSerializer->ReadString( mValue );
}
void cFCOPropInt32::Read(iSerializer* pSerializer, int32 version)
{
    if (version > 0)
        ThrowAndAssert(eSerializerVersionMismatch(_T("Int32 Property Read")));

    pSerializer->ReadInt32(mValue);
}
TSTRING cNonPrintableCharEncoder::Decode(  TSTRING::const_iterator* pcur, 
                                     const TSTRING::const_iterator  end  ) const
{
    // check preconditions
    if( (*pcur) >= end || *(*pcur) != Identifier() )
        ThrowAndAssert( eBadDecoderInput() );

    return( cCharEncoderUtil::DecodeHexToChar( pcur, end ) );
}
void cFSObject::Read(iSerializer* pSerializer, int32 version)
{
	if (version > Version())
		ThrowAndAssert(eSerializerVersionMismatch(_T("File System Object")));

	
	pSerializer->ReadObject(&mName);
	pSerializer->ReadObject(&mPropSet);
}
TSTRING cBackslashCharEncoder::Decode(  TSTRING::const_iterator* pcur, 
                                  const TSTRING::const_iterator  end  ) const
{
    if( (*pcur) >= end || *(*pcur) != Identifier() )
        ThrowAndAssert( eBadDecoderInput() );

    (*pcur)++; // advance past part decoded

    return TSTRING( 1, Identifier() );
}
void cFCOSpecImpl::Read(iSerializer* pSerializer, int32 version)
{
    if (version > Version())
        ThrowAndAssert(eSerializerVersionMismatch(_T("FS Spec Read")));

    pSerializer->ReadString(mName);
    mPropVector.Read(pSerializer);

    // read the helper
    mpHelper = (iFCOSpecHelper*)pSerializer->ReadObjectDynCreate();
}
iTWFactory* cGenreSwitcher::GetFactoryForGenre(cGenre::Genre g)
{
    cGenreInfoVec::const_iterator i = m_vGenres.find(g);

    if (i == m_vGenres.end())
    {
        ThrowAndAssert(INTERNAL_ERROR("Switch to invalid genre factory"));
    }

    ASSERT((*i)->m_pFactory != NULL);
    return ((*i)->m_pFactory);
}
///////////////////////////////////////////////////////////////////////////////
// Read
///////////////////////////////////////////////////////////////////////////////
void cFCODatabaseFile::Read(iSerializer* pSerializer, int32 version)
{
    if (version > Version())
        ThrowAndAssert(eSerializerVersionMismatch(_T("Database Read")));
    
    //
    // read the db header..
    //
    pSerializer->ReadObject( &mHeader );

    int32 numGenre;
    pSerializer->ReadInt32( numGenre );
    for( int i=0; i < numGenre; i++ )
    {
        // read the genre number and throw if it is incorrect
        //
        int32 iGenre;
        pSerializer->ReadInt32( iGenre );
        cGenre::Genre genre = (cGenre::Genre) iGenre;

        if( ! cGenreSwitcher::GetInstance()->IsGenreRegistered( genre ) )
        {
            throw eSerializerInputStreamFmt(_T("Encountered unknown genre.  Can not read database on this platform."), mFileName, eSerializer::TY_FILE);
        }

        mDbList.push_back( new tEntry( genre ) );
        tEntry& entry = *(mDbList.back());
        //
        // read the db genre header..
        //
        pSerializer->ReadObject( &entry.mGenreHeader );
        //
        // get the spec list
        //
        pSerializer->ReadObject( &entry.mSpecList );
        //
        // get the database data
        //
        int32 fileSize;
        pSerializer->ReadInt32( fileSize );
        //
        // write the hier database into a temp file...
        //
        cLockedTemporaryFileArchive* pArch = new cLockedTemporaryFileArchive();
        pArch->OpenReadWrite();

        cSerializerUtil::Copy( pArch, pSerializer, fileSize );
        //
        // associate the database with this file...
        //
        entry.mDb.Open( pArch );
    }
}
示例#11
0
void cFSPropSet::Read(iSerializer* pSerializer, int32 version)
{
    if (version > Version())
        ThrowAndAssert(eSerializerVersionMismatch(_T("FS Property Set Read")));

    mValidProps.Read(pSerializer);
    mUndefinedProps.Read(pSerializer);

    for (int i=0; i < PROP_NUMITEMS; i++)
    {
        if (mValidProps.ContainsItem(i) && !mUndefinedProps.ContainsItem(i))
            GetPropAt(i)->Read(pSerializer);
    }
}
// Add an object to the table, optionally specifying an ID. Returns a 
// unique ID for the object.  ASSERTs and throws exception if object is 
// already in table or the ID is already taken.
int cSerRefCountTable::Add(iSerRefCountObj* pObj, int id)
{
    if (Lookup(pObj) != 0)
    {
		// this should be a programming error, but we will throw just to be safe...
		ThrowAndAssert(eInternal(_T("cSerRefCountTable::Add() passed object already in table.")));
    }
    if (id == 0)
    {
        id = mIDToObjTbl.empty() ? 1 : mIDToObjTbl.rbegin()->first + 1;
        ASSERT(Lookup(id) == NULL);
    }
    else if (Lookup(id) != NULL)
    {
		// this should be a programming error, but we will throw just to be safe...
		ThrowAndAssert(eInternal(_T("cSerRefCountTable::Add() passed ID already in table.")));
    }

    mIDToObjTbl.insert( MapIDTObj::value_type(id, pObj));
    mObjToIdTbl.insert( MapObjIDT::value_type(pObj, id));

    return id;
}
TCHAR cCharEncoderUtil::hex_to_char( TSTRING::const_iterator first, 
                                     TSTRING::const_iterator last )
{
    static const TCHAR max_char = std::numeric_limits<TCHAR>::max();
    static const TCHAR min_char = std::numeric_limits<TCHAR>::min();

    if( first + TCHAR_AS_HEX__IN_TCHARS != last )
        ThrowAndAssert( eBadHexConversion() );

    TISTRINGSTREAM ss( TSTRING( first, last ) );
    ss.imbue( std::locale::classic() );
    ss.fill ( _T('0') );
    ss.setf( std::ios_base::hex, std::ios_base::basefield );

    unsigned long ch;
    ss >> ch;
    
    if( ss.bad() || ss.fail() )
        ThrowAndAssert( eBadHexConversion( TSTRING( first, last ) ) );
    if( (TCHAR)ch > max_char || (TCHAR)ch < min_char )
        ThrowAndAssert( eBadHexConversion( TSTRING( first, last ) ) );

    return (TCHAR)ch;
}
TSTRING cCharEncoderUtil::char_to_hex( TCHAR ch )
{
    TOSTRINGSTREAM ss;

    ss.imbue( std::locale::classic() );
    ss.fill ( _T('0') );
    ss.width( TCHAR_AS_HEX__IN_TCHARS );
    ss.setf( std::ios_base::hex, std::ios_base::basefield );

    ss << tss::util::char_to_size( ch );

    if( ss.bad() || ss.fail() || 
        ss.str().length() != TCHAR_AS_HEX__IN_TCHARS )
        ThrowAndAssert( eBadHexConversion( TSTRING( 1, ch ) ) );
    return ss.str();
}
void cGenreHeaderInfo::Read(iSerializer* pSerializer, int32 version) // throw (eSerializer, eArchive)
{
    if (version > Version())
        ThrowAndAssert(eSerializerVersionMismatch(_T("cHeaderInfo Read")));

    // read the prop displayer
    ASSERT(mpPropDisplayer == 0);

    int32 fMakePD;
    pSerializer->ReadInt32(fMakePD);

    if (fMakePD == 1)
        mpPropDisplayer = static_cast<iFCOPropDisplayer*>(pSerializer->ReadObjectDynCreate());

    pSerializer->ReadInt32(i32_ObjectsScanned);
}
void cHeaderInfo::Read(iSerializer* pSerializer, int32 version) // throw (eSerializer, eArchive)
{
    if (version > Version())
        ThrowAndAssert(eSerializerVersionMismatch(_T("cHeaderInfo Read")));

    pSerializer->ReadString(tstr_SystemName);
    pSerializer->ReadString(tstr_PolicyFilename);
    pSerializer->ReadString(tstr_ConfigFilename);
    pSerializer->ReadString(tstr_DBFilename);
    pSerializer->ReadString(tstr_CommandLineParams);
    pSerializer->ReadString(tstr_CreatedBy);
    pSerializer->ReadString(tstr_IPAddress);
    pSerializer->ReadString(tstr_HostID);
    pSerializer->ReadInt64(i64_CreationTime);
    pSerializer->ReadInt64(i64_LastDBUpdateTime);
}
示例#17
0
///////////////////////////////////////////////////////////////////////////////
// ReadPolicyText
//
// Read the policy file.  Read the text of a policy language into configText
// Will throw eError on failure.
///////////////////////////////////////////////////////////////////////////////
void cTWUtil::ReadPolicyText(const TCHAR* filename, std::string& polText, const cElGamalSigPublicKey* pPublicKey)
{
    cSerializableNString nstring;

    cFileUtil::TestFileExists(filename);

    bool bEncrypted;
    ReadObject(filename, NULL, nstring, cPolicyFile::GetFileHeaderID(), pPublicKey, bEncrypted);

    // check 8 byte header
    if (nstring.mString.compare(0, 8 * sizeof(byte), POLICY_FILE_MAGIC_8BYTE) != 0)
        ThrowAndAssert(eSerializerInputStreamFmt(_T(""), filename, eSerializer::TY_FILE));

    // remove 8 byte header
    nstring.mString.assign(nstring.mString.substr(8));

    polText = nstring.mString;
}
TSTRING cCharEncoderUtil::DecodeHexToChar(  TSTRING::const_iterator* pcur, 
                                      const TSTRING::const_iterator  end  )
{
    // get hex numbers -- 2 chars
    TSTRING str;
    size_t n = 0;
    for( (*pcur)++; 
         n < TCHAR_AS_HEX__IN_TCHARS && 
             (*pcur) != end; 
         n++, (*pcur)++ )
    {
        str += *(*pcur);
    }

    if( n != TCHAR_AS_HEX__IN_TCHARS )
        ThrowAndAssert( eBadDecoderInput() );

    // convert hex numbers
    return HexValueToCharString( str );
}
示例#19
0
///////////////////////////////////////////////////////////////////////////////
// AcceptSerializer 
///////////////////////////////////////////////////////////////////////////////
void cFCOSetImpl::Read(iSerializer* pSerializer, int32 version)
{
    if (version > Version())
        ThrowAndAssert(eSerializerVersionMismatch(_T("FCO Set Read")));

    Clear();

    int i;
    int32 size;
    pSerializer->ReadInt32(size);
    
    // TODO -- don't assert; throw an exception or noop -- mdb
    //ASSERT(size >= 0);

    for (i = 0; i < size; ++i)
    {
        iTypedSerializable* pObj = pSerializer->ReadObjectDynCreate();
        mFCOSet.insert(static_cast<iFCO*>(pObj));
    }
}
示例#20
0
///////////////////////////////////////////////////////////////////////////////
// WriteObjectToArchive -- called from WriteObject, does most of the work
///////////////////////////////////////////////////////////////////////////////
static void ReadObjectFromArchive(cArchive&                   arch,
                                  const TCHAR*                objFileName,
                                  iTypedSerializable*         pObjHeader,
                                  iTypedSerializable&         obj,
                                  const cFileHeaderID&        fhid,
                                  const cElGamalSigPublicKey* pPublicKey,
                                  bool&                       bEncrypted)
{
    cFileHeader fileHeader;

    {
        cSerializerImpl fhSer(arch, cSerializerImpl::S_READ, objFileName);
        fileHeader.Read(&fhSer);
    }

    // check for a mismatched header
    if (fileHeader.GetID() != fhid)
        ThrowAndAssert(eSerializerInputStreamFmt(_T(""), objFileName, eSerializer::TY_FILE));

    // Check file version.
    // If we in the future we wish to support reading objects of different versions,
    // we will have to move this check to outside ReadObject().
    if (fileHeader.GetVersion() != CURRENT_FIXED_VERSION)
        ThrowAndAssert(eSerializerVersionMismatch(_T(""), objFileName, eSerializer::TY_FILE));

    try
    {
        // switch on the type of encoding...
        if (fileHeader.GetEncoding() == cFileHeader::ASYM_ENCRYPTION)
        {
            // tell the user the db is encrypted
            iUserNotify::GetInstance()->Notify(iUserNotify::V_VERBOSE,
                                               TSS_GetString(cTW, tw::STR_FILE_ENCRYPTED).c_str());
            bEncrypted = true;

            if (pPublicKey == 0)
                ThrowAndAssert(eSerializerEncryption(_T("")));

            cElGamalSigArchive cryptoArchive;
            cryptoArchive.SetRead(&arch, pPublicKey);

            cSerializerImpl ser(cryptoArchive, cSerializerImpl::S_READ, objFileName);
            ser.Init();
            if (pObjHeader)
                ser.ReadObject(pObjHeader);
            ser.ReadObject(&obj);
            ser.Finit();
        }
        else if (fileHeader.GetEncoding() == cFileHeader::COMPRESSED)
        {
            //not encrypted db...
            bEncrypted = false;

            cNullCryptoArchive cryptoArchive;
            cryptoArchive.Start(&arch);

            cSerializerImpl ser(cryptoArchive, cSerializerImpl::S_READ, objFileName);
            ser.Init();
            if (pObjHeader)
                ser.ReadObject(pObjHeader);
            ser.ReadObject(&obj);
            ser.Finit();
        }
        else
            // unknown encoding...
            ThrowAndAssert(eSerializerInputStreamFmt(_T("")));
    }
    catch (eError& e)
    {
        // include filename in error msg
        throw ePoly(e.GetID(), cErrorUtil::MakeFileError(e.GetMsg(), objFileName), e.GetFlags());
    }
}
void cEncoder::Decode( TSTRING& strIn ) const
{
    // TODO:BAM -- reserve space for strOut as an optimization?
    TSTRING strOut;         // decoded string we will build up

    TSTRING::const_iterator         cur = strIn.begin();  // pointer to working position in strIn
    const TSTRING::const_iterator   end = strIn.end();    // end of strIn
    TSTRING::const_iterator         first = end;          // identifies beginning of current character
    TSTRING::const_iterator         last  = end;          // identifies end of current character
    

    // while get next char (updates cur)
    while( cCharUtil::PopNextChar( cur, end, first, last ) )
    {
        // is this char the escape character?
        if( IsSingleTCHAR( first, last ) && 
            *first == iCharEncoder::EscapeChar() )
        {
            // get to identifier
            if( ! cCharUtil::PopNextChar( cur, end, first, last ) )
                ThrowAndAssert( eBadDecoderInput() );
            
            // this algorithm assumes that all identifiers are single char
            // so anything following the escape char should be a 
            // single-char identifier
            if( ! IsSingleTCHAR( first, last ) ) 
                THROW_INTERNAL( "displayencoder.cpp" );

            // determine to which encoding the identifier belongs
            bool fFoundEncoding = false;
            sack_type::const_iterator atE;
            for( atE = m_encodings.begin(); 
                 atE != m_encodings.end(); 
                 atE++ )
            {
                // is this the right encoding?
                if( *first == (*atE)->Identifier() )
                {
                    // this is the correct encoding....
                    fFoundEncoding = true;

                    // ...so decode char
                    strOut += (*atE)->Decode( &first, end ); // should modify cur
                    
                    cur = first; // advance current char pointer

                    break;  // no need to run other tests after 
                            // this because all identifiers should be unique
                }
            }

            if( ! fFoundEncoding )
                ThrowAndAssert( eUnknownEscapeEncoding( TSTRING( 1, *first ) ) );
        }
        else
        {        
            strOut.append( first, last );
        }
    }

    strIn = strOut;
}
示例#22
0
void cTWUtil::ReadConfigText(const TCHAR* filename, TSTRING& configText, cArchive* pBaggage)
{
    // TODO -- neat up this function; try to use LoadObject() above...

    cSerializableNString nstring;

    // This was coppied from ReadObject().  We need to use the baggage of the
    // file header to obtain the public key, thus the special casing.
    cDebug d("ReadConfigText");
    d.TraceDebug(_T("Reading %s from file %s\n"), nstring.GetType().AsString(), filename);

    iUserNotify::GetInstance()->Notify(iUserNotify::V_VERBOSE,
                                       _T("%s%s\n"),
                                       TSS_GetString(cTW, tw::STR_OPEN_CONFIG_FILE).c_str(),
                                       cDisplayEncoder::EncodeInline(filename).c_str());

    cFileArchive arch;
    arch.OpenRead(filename);

    cFileHeader fileHeader;

    try
    {
        cSerializerImpl fhSer(arch, cSerializerImpl::S_READ);
        fileHeader.Read(&fhSer);
    }
    catch (eError&)
    {
        throw eSerializerInputStreamFmt(_T(""), filename, eSerializer::TY_FILE);
    }

#if 0 // XXX: This is broken, what the h*ll are they trying to write here? -PH
    d.TraceDebug("Found a file header of type %d.\n", fileHeader.GetEncoding());
#endif

    // check for a mismatched header
    if (fileHeader.GetID() != cConfigFile::GetFileHeaderID())
        throw eSerializerInputStreamFmt(_T(""), filename, eSerializer::TY_FILE);

    // check the version
    if (fileHeader.GetVersion() != CURRENT_FIXED_VERSION)
        throw eSerializerVersionMismatch(_T(""), filename, eSerializer::TY_FILE);

    // switch on the type of encoding...
    if (fileHeader.GetEncoding() == cFileHeader::ASYM_ENCRYPTION)
    {
        d.TraceDebug("Config file is compressed, public key len %d.\n", fileHeader.GetBaggage().Length());

        // tell the user the db is encrypted
        iUserNotify::GetInstance()->Notify(iUserNotify::V_VERBOSE, TSS_GetString(cTW, tw::STR_FILE_ENCRYPTED).c_str());
        iUserNotify::GetInstance()->Notify(iUserNotify::V_VERBOSE, TSS_GetString(cTW, tw::STR_NEWLINE).c_str());

        ASSERT(fileHeader.GetBaggage().Length() > 0);
        if (fileHeader.GetBaggage().Length() <= 0)
            ThrowAndAssert(eSerializerInputStreamFmt(_T(""), filename, eSerializer::TY_FILE));

        fileHeader.GetBaggage().MapArchive(0, fileHeader.GetBaggage().Length());

        cElGamalSigPublicKey publicKey(fileHeader.GetBaggage().GetMap());

        cElGamalSigArchive cryptoArchive;
        cryptoArchive.SetRead(&arch, &publicKey);

        cSerializerImpl ser(cryptoArchive, cSerializerImpl::S_READ);
        ser.Init();
        ser.ReadObject(&nstring);
        ser.Finit();

        // copy the baggage into the archive, if it was passed in
        // Note: We rely in VerifySiteKey that we only fill out pBaggage if
        // the config file is encrypted.
        //
        if (pBaggage)
        {
            fileHeader.GetBaggage().Seek(0, cBidirArchive::BEGINNING);
            pBaggage->Copy(&fileHeader.GetBaggage(), fileHeader.GetBaggage().Length());
        }
    }
    else if (fileHeader.GetEncoding() == cFileHeader::COMPRESSED)
    {
        d.TraceDebug("Config file is not compressed.\n");

        //not encrypted db...
        cNullCryptoArchive cryptoArchive;
        cryptoArchive.Start(&arch);

        cSerializerImpl ser(cryptoArchive, cSerializerImpl::S_READ);
        ser.Init();
        ser.ReadObject(&nstring);
        ser.Finit();
    }
    else
        // unknown encoding...
        throw eSerializerInputStreamFmt(_T(""), filename, eSerializer::TY_FILE);

    // check 8 byte header
    if (nstring.mString.compare(0, 8 * sizeof(byte), CONFIG_FILE_MAGIC_8BYTE) != 0)
        ThrowAndAssert(eSerializerInputStreamFmt(_T(""), filename, eSerializer::TY_FILE));

    // remove 8 byte header
    nstring.mString.assign(nstring.mString.substr(8));

    cStringUtil::Convert(configText, nstring.mString);
}