Exemplo n.º 1
0
TEST(ErrorCheck, CalcCRC_Data_ProcessMultiBytesSize)
{
  uint8_t buffer[2];
  buffer[0] = 1;
  buffer[1] = 2;
	TEST_ASSERT_EQUAL(4979, CalcCRC(buffer, 2));
}
Exemplo n.º 2
0
//---------------------------------------------------------------------------
USHORT __fastcall AddCRC(USHORT d, const BYTE *p, int n)
{
	for( ; n; n--, p++ ){
		d = CalcCRC(d, *p);
	}
	return d;
}
Exemplo n.º 3
0
void BulkStorage_WriteClose(struct BulkStorage *b)
{
  if ( b == NULL ) {
    return;
  }
  if ( b->dirty != 0 ) {
    WritePage(b);
  }
  if ( b->marked != 0 ) {
    uint32_t image_hash = 0;
    uint32_t page_hash ;
    for ( uint32_t i = 1; i < b->token->number_pages ; i ++ ) {
      ReadPage(b,  i);
      page_hash = CalcCRC(b->data, DATAFLASH_PAGESIZE_NORMAL);
      image_hash ^= page_hash;      
    }
    b->head.hash = image_hash;
    b->head.timestamp = 0;
    b->marked = 0;
    WriteHeader(b->token, &b->head);
  }
  
  b->token = NULL;
  b->loaded_page = 0xFFFF;
  b->dirty = 0;
  b->write = 0;
}
Exemplo n.º 4
0
/**
 * Decode incoming byte from incoming packet
 *
 * \param data Byte from incoming packet
 */
void Stream::Decode(uint8_t data)
{
	switch(this->rx_next)
	{
		case(next_startbyte):
			if (data == xlib_stream_startbyte)
				this->rx_next++;
				this->buffer->Clear();
		return;
		case(next_length):
			this->rx_length = data;
			if (data == 0)
				this->rx_next = next_startbyte;
			else
				this->rx_next++;
		return;
		case(next_length_check):
			if (data == this->rx_length)
			{
				this->rx_crc = CalcCRC(0x00, xlib_stream_crc_key, data);
				this->rx_next++;
			}
			else
				this->rx_next = next_startbyte;
		return;
		case(next_data):
			this->rx_length--;
			this->buffer->Write(data);
			this->rx_crc = CalcCRC(this->rx_crc, xlib_stream_crc_key, data);
			if (this->rx_length == 0)
				this->rx_next++;
		return;
		case(next_crc):
			if (this->rx_crc != data)
			{
				this->buffer->Clear();
			}
			else
			{
				if (Stream::onPacket != NULL)
					Stream::onPacket();
			}
			this->rx_next = next_startbyte;
		return;

	}
}
Exemplo n.º 5
0
static void WritePage(struct BulkStorage *b)
{
  struct PageBuf p;
  memcpy(p.buf, b->data, DATAFLASH_PAGESIZE_NORMAL);
  p.hash = CalcCRC(p.buf, DATAFLASH_PAGESIZE_NORMAL);
  DataFlash_BufferWrite(b->token, b->loaded_page, 0, sizeof(struct PageBuf), DATAFLASH_FLASHBUF1, (uint8_t*) &p); 
  DataFlash_WriteBufferToFlash(b->token, b->loaded_page, DATAFLASH_FLASHBUF1);
}
Exemplo n.º 6
0
//---------------------------------------------------------------------------
USHORT __fastcall GetCRC(LPCSTR p)
{
	USHORT d = 0;
	for( ; *p; p++ ){
		d = CalcCRC(d, *p);
	}
	if( !d ) d++;
	return d;
}
Exemplo n.º 7
0
uint16_t CompareCalcCRC(const uint8_t * buffer, uint32_t size, uint16_t crc)
{
  uint16_t calc =  CalcCRC(buffer, size);
  if ( calc == 0 ) {
    return 0;
  } else if ( calc == crc ) {
    return 1;
  } else {
    return 0;
  }
}
Exemplo n.º 8
0
/**
 * Write one byte to outgoing packet
 *
 * \param data Data byte to be send
 * \note method StartPacket() should be used before using this method
 */
void Stream::Write(uint8_t data)
{
	if (this->tx_length == 0)
		return;

	this->tx_crc = CalcCRC(this->tx_crc, xlib_stream_crc_key, data);
	fputc(data, this->output);
	this->tx_length--;

	if (this->tx_length == 0)
		fputc(this->tx_crc, this->output);
}
Exemplo n.º 9
0
bool PSIPTable::VerifyPSIP(bool verify_crc) const
{
    if (verify_crc && (CalcCRC() != CRC()))
    {
        LOG(VB_SIPARSER, LOG_ERR,
            QString("PSIPTable: Failed CRC check 0x%1 != 0x%2 "
                    "for StreamID = 0x%3")
                .arg(CRC(),0,16).arg(CalcCRC(),0,16).arg(StreamID(),0,16));
        return false;
    }

    unsigned char *bufend = _fullbuffer + _allocSize;

    if ((_pesdata + 2) >= bufend)
        return false; // can't query length

    if (psipdata() >= bufend)
        return false; // data outside buffer

    if (TableID::PAT == TableID())
    {
        uint pcnt = (SectionLength() - PSIP_OFFSET - 2) >> 2;
        bool ok = (psipdata() + (pcnt << 2) + 3 < bufend);
        if (!ok)
        {
            LOG(VB_SIPARSER, LOG_ERR,
                "PSIPTable: PAT: program list extends past end of buffer");
            return false;
        }

        if ((Length() == 0xfff) && (TableIDExtension() == 0xffff) &&
            (Section() == 0xff) && (LastSection() == 0xff))
        {
            LOG(VB_SIPARSER, LOG_ERR, "PSIPTable: PAT: All values at maximums");
            return false;
        }

        return true;
    }
Exemplo n.º 10
0
/**
 * Start outgoing packet with specified length
 *
 * \param length Length of outgoing packet
 */
void Stream::StartPacket(uint8_t length)
{
	while(this->tx_length > 0)
		this->Write(0x00);

	//header
	fputc(xlib_stream_startbyte ,this->output);
	fputc(length ,this->output);
	fputc(length ,this->output);

	this->tx_crc = CalcCRC(0x00, xlib_stream_crc_key, length);
	this->tx_length = length;
}
Exemplo n.º 11
0
// convert chunk to its original network ordering
void CCapsLoader::ConvertChunk(PCAPSCHUNK pc)
{
	if (!pc)
		return;

	// set complete chunk to network byte order
	int ofs=sizeof(pc->cg.file.name);
	int size=pc->cg.file.size;
	Swap(PUDWORD((PUBYTE)&pc->cg.file+ofs), size-ofs);

	// calculate crc and set to network byte order
	pc->cg.file.hcrc=0;
	pc->cg.file.hcrc=CalcCRC((PUBYTE)&pc->cg.file, size);
	CCapsLoader::Swap(&pc->cg.file.hcrc, sizeof(pc->cg.file.hcrc));
}
Exemplo n.º 12
0
	bool CalcFileHash(LPCWSTR asFile, DWORD& size, DWORD& crc)
	{
		bool bRc = false;
		HANDLE hFile;
		LARGE_INTEGER liSize = {};
		const DWORD nBufSize = 0x10000;
		BYTE* buf = new BYTE[nBufSize];
		DWORD nReadLeft, nRead, nToRead;

		crc = 0xFFFFFFFF;

		hFile = CreateFile(asFile, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
		if (!hFile || hFile == INVALID_HANDLE_VALUE)
		{
			Sleep(250);
			hFile = CreateFile(asFile, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
			if (!hFile || hFile == INVALID_HANDLE_VALUE)
				goto wrap;
		}

		if (!GetFileSizeEx(hFile, &liSize) || liSize.HighPart)
			goto wrap;

		size = liSize.LowPart;
		nReadLeft = liSize.LowPart;

		while (nReadLeft)
		{
			nToRead = min(nBufSize, nReadLeft);
			if (!ReadFile(hFile, buf, nToRead, &nRead, NULL) || (nToRead != nRead))
				goto wrap;
			if (!CalcCRC(buf, nRead, crc))
				goto wrap;
			_ASSERTE(nReadLeft >= nRead);
			nReadLeft -= nRead;
		}

		// Succeeded
		crc ^= 0xFFFFFFFF;
		bRc = true;
	wrap:
		delete[] buf;
		if (!hFile || hFile == INVALID_HANDLE_VALUE)
			CloseHandle(hFile);
		return bRc;
	};
Exemplo n.º 13
0
uint8_t BulkStorage_VerifyImage(const DFToken_t *token)
{
  struct PageBuf p;
  uint32_t i;
  uint32_t page_hash;
  uint32_t image_hash = 0;

  struct BulkStorage_Header h;
  ReadHeader(token, &h);
  
  for ( i = 1; i < token->number_pages; i ++ ) {
    DataFlash_PageRead(token, i, 0, sizeof(struct PageBuf), (uint8_t*)&p);
    page_hash = CalcCRC(p.buf, DATAFLASH_PAGESIZE_NORMAL);   
    if ( page_hash != p.hash ) {
      return 0;
    }
    image_hash ^= page_hash;   
  }
  return ( image_hash == h.hash )? 1: 0;
}
Exemplo n.º 14
0
// calculate CRC32 on file
UDWORD CDiskImage::CrcFile(PCAPSFILE pcf)
{
	UDWORD crc=0;

	// shortcut for memory files
	if (pcf->flag & CFF_MEMMAP) {
		if (!pcf->memmap || pcf->size<0)
			return crc;

		return CalcCRC(pcf->memmap, pcf->size);
	}

	// open file
	CCapsFile file;
	if (file.Open(pcf))
		return crc;

	int len=file.GetSize();

	if (len) {
		int bufsize=DEF_CRCBUF;
		PUBYTE buf=new UBYTE[bufsize];

		// calculate CRC32 on file
		while (len) {
			int size=len > bufsize ? bufsize : len;
			if (file.Read(buf, size) != size) {
				crc=0;
				break;
			}

			crc=CalcCRC32(buf, size, crc);
			len-=size;
		}

		delete [] buf;
	}

	return crc;
}
Exemplo n.º 15
0
// read data area of data chunk
int CCapsLoader::ReadData(PUBYTE buf)
{
	// handle file error
	if (!file.IsOpen())
		return 0;

	// do not read next time, clear type
	int type=chunk.type;
	chunk.type=ccidUnknown;

	// skip only data area
	if (type != ccidData)
		return 0;

	// do not skip empty area
	int size=chunk.cg.mod.data.size;
	if (!size)
		return 0;

	// correct and skip size if image is short
	int pos=file.GetPosition();
	if (flen-pos < size) {
		size=flen-pos;

		// seek to new chunk
		file.Seek(size, 0);
		return 0;
	}

	// read data area
	if (file.Read(buf, size) != size)
		return 0;

	// check data CRC if available
	if (chunk.cg.mod.data.dcrc)
		if (chunk.cg.mod.data.dcrc != CalcCRC(buf, size))
			return 0;

	return size;
}
Exemplo n.º 16
0
//-----------------------------------------------------------------------------
// Purpose: Writes stat file.  Used as primary storage for X360.  For PC,
//			Steam is authoritative but we write stat file for debugging (although
//			we never read it).
//-----------------------------------------------------------------------------
void CTFStatPanel::WriteStats( void )
{
	if ( !m_bStatsChanged )
		return;

	MEM_ALLOC_CREDIT();

	DECLARE_DMX_CONTEXT();
	CDmxElement *pPlayerStats = CreateDmxElement( "PlayerStats" );
	CDmxElementModifyScope modify( pPlayerStats );

	// get Steam ID.  If not logged into Steam, use 0
	int iSteamID = 0;
	if ( SteamUser() )
	{
		CSteamID steamID = SteamUser()->GetSteamID();
		iSteamID = steamID.GetAccountID();
	}	
	// Calc CRC of all data to make the local data file somewhat tamper-resistant
	int iCRC = CalcCRC( iSteamID );

	pPlayerStats->SetValue( "iVersion", static_cast<int>( PLAYERSTATS_FILE_VERSION ) );
	pPlayerStats->SetValue( "SteamID", iSteamID );	
	pPlayerStats->SetValue( "iTimestamp", iCRC );	// store the CRC with a non-obvious name

	CDmxAttribute *pClassStatsList = pPlayerStats->AddAttribute( "aClassStats" );
	CUtlVector< CDmxElement* >& classStats = pClassStatsList->GetArrayForEdit<CDmxElement*>();

	modify.Release();

	for( int i = 0; i < m_aClassStats.Count(); i++ )
	{
		const ClassStats_t &stat = m_aClassStats[ i ];

		// strip out any garbage class data
		if ( ( stat.iPlayerClass > TF_LAST_NORMAL_CLASS ) || ( stat.iPlayerClass < TF_FIRST_NORMAL_CLASS ) )
			continue;

		CDmxElement *pClass = CreateDmxElement( "ClassStats_t" );
		classStats.AddToTail( pClass );

		CDmxElementModifyScope modifyClass( pClass );

		pClass->SetValue( "comment: classname", g_aPlayerClassNames_NonLocalized[ stat.iPlayerClass ] );
		pClass->AddAttributesFromStructure( &stat, s_ClassStatsUnpack );
		
		CDmxElement *pAccumulated = CreateDmxElement( "RoundStats_t" );
		pAccumulated->AddAttributesFromStructure( &stat.accumulated, s_RoundStatsUnpack );
		pClass->SetValue( "accumulated", pAccumulated );

		CDmxElement *pMax = CreateDmxElement( "RoundStats_t" );
		pMax->AddAttributesFromStructure( &stat.max, s_RoundStatsUnpack );
		pClass->SetValue( "max", pMax );
	}

	if ( IsX360() )
	{
#ifdef _X360
		if ( XBX_GetStorageDeviceId() == XBX_INVALID_STORAGE_ID || XBX_GetStorageDeviceId() == XBX_STORAGE_DECLINED )
			return;
#endif
	}

	char szFilename[_MAX_PATH];

	if ( IsX360() )
		Q_snprintf( szFilename, sizeof( szFilename ), "cfg:/tf2_playerstats.dmx" );
	else
		Q_snprintf( szFilename, sizeof( szFilename ), "tf2_playerstats.dmx" );

	{
		MEM_ALLOC_CREDIT();
		CUtlBuffer buf( 0, 0, CUtlBuffer::TEXT_BUFFER );
		if ( SerializeDMX( buf, pPlayerStats, szFilename ) )
		{
			filesystem->WriteFile( szFilename, "MOD", buf );
		}
	}

	CleanupDMX( pPlayerStats );

	if ( IsX360() )
	{
		xboxsystem->FinishContainerWrites();
	}

	m_bStatsChanged = false;
}
Exemplo n.º 17
0
BOOL DBItemList::Save(VOID* pSource)
{
	__ENTER_FUNCTION

	INT Result;
	Delete();
	ParseResult(&Result);

	enum 
	{
		DB_CharGuid	=	1,
		DB_ItemWorld,
		DB_ItemServer,
		DB_ItemGuid,
		DB_ItemType,
		DB_ItemPos,
		DB_FixAttr,  //也可以去掉,但是Login 需要读装备表
		DB_P1,
		DB_P2,
		DB_P3,
		DB_P4,
		DB_P5,
		DB_P6,
		DB_P7,
		DB_P8,
		DB_P9,
		DB_P10,
		DB_P11,
		DB_P12,
		DB_P13,
		DB_P14,
	};


	FULLUSERDATA* pCharFullData = static_cast<FULLUSERDATA*>(pSource);
	Assert(pCharFullData);

	for(INT ItemPos =0;ItemPos<=DB_BANK_POS_END;ItemPos++)
	{
		if( ItemPos >= DB_BAG_POS_START && ItemPos < (DB_BAG_POS_START+MAX_BAG_SIZE) )
		{
			//背包
		}
		else if( ItemPos >= DB_EQUIP_POS_START && ItemPos < (DB_EQUIP_POS_START+HEQUIP_NUMBER) )
		{
			//装备
		}
		else if( ItemPos >= DB_BANK_POS_START && ItemPos < (DB_BANK_POS_START+MAX_BANK_SIZE) )
		{
			//银行
		}
		else
		{
			continue;
		}

		_ITEM* pItem = pCharFullData->GetItem(ItemPos);
		
		if(pItem->IsNullType()) continue;

		DB_QUERY* pQuery = GetInternalQuery();

		if(!pQuery)
		{
			Assert(FALSE);
		}

		pQuery->Clear();

		if(m_CharGuid==INVALID_ID)
		{
			return FALSE;
		}
		
		CHAR FixAttr[MAX_FIX_ATTR_LENGTH];
		CHAR FixAttrOut[MAX_FIX_ATTR_LENGTH];
		memset(FixAttrOut,0,MAX_FIX_ATTR_LENGTH);
		INT  OutLength;
		pItem->ReadFixAttr(FixAttr,OutLength,MAX_FIX_ATTR_LENGTH);
		Binary2String(FixAttr,OutLength,FixAttrOut);

		INT PArray[14] = {0};

		pItem->ReadVarAttr((CHAR*)PArray,OutLength,sizeof(INT)*(DB_P14-DB_P1+1));

		CHAR VarAttr[256] = {0};
		Binary2String((CHAR*)(pItem->m_Param),sizeof(INT)*MAX_ITEM_PARAM,VarAttr);

		UINT dbVersion = CalcCRC((CHAR*)PArray);
		pQuery->Parse(NewCharItem,
			// ITEM_TABLE,
			m_CharGuid,	//charguid
			pItem->m_ItemGUID.m_Serial,
			pItem->m_ItemGUID.m_World,
			pItem->m_ItemGUID.m_Server,
			pItem->m_ItemIndex,
			ItemPos,
			FixAttrOut,
			PArray[0],
			PArray[1],
			PArray[2],
			PArray[3],
			PArray[4],
			PArray[5],
			PArray[6],
			PArray[7],
			PArray[8],
			PArray[9],
			PArray[10],
			PArray[11],
			PArray[12],
			PArray[13],
			1,
			dbVersion,
			pItem->m_Creator,
			VarAttr);

		if(!ODBCBase::Save(pCharFullData))
			return FALSE;


	}
	return TRUE;

	__LEAVE_FUNCTION

	return FALSE;
}
Exemplo n.º 18
0
void STORCommand::Execute()
{
  namespace pt = boost::posix_time;
  namespace gd = boost::gregorian;
  
  fs::VirtualPath path(fs::PathFromUser(argStr));
  
  util::Error e(acl::path::Filter(client.User(), path.Basename()));
  if (!e)
  {
    control.Reply(ftp::ActionNotOkay, "File name contains one or more invalid characters.");
    throw cmd::NoPostScriptError();
  }

  off_t offset = data.RestartOffset();
  if (offset > 0 && data.DataType() == ftp::DataType::ASCII)
  {
    control.Reply(ftp::BadCommandSequence, "Resume not supported on ASCII data type.");
    throw cmd::NoPostScriptError();
  }
  
  if (!exec::PreCheck(client, path)) throw cmd::NoPostScriptError();

  switch(ftp::Counter::Upload().Start(client.User().ID(), 
         client.User().MaxSimUp(), 
         client.User().HasFlag(acl::Flag::Exempt)))
  {
    case ftp::CounterResult::PersonalFail  :
    {
      std::ostringstream os;
      os << "You have reached your maximum of " << client.User().MaxSimUp() 
         << " simultaneous uploads(s).";
      control.Reply(ftp::ActionNotOkay, os.str());
      throw cmd::NoPostScriptError();
    }
    case ftp::CounterResult::GlobalFail    :
    {
      control.Reply(ftp::ActionNotOkay, 
          "The server has reached it's maximum number of simultaneous uploads.");
      throw cmd::NoPostScriptError();          
    }
    case ftp::CounterResult::Okay          :
      break;
  }  
  
  auto countGuard = util::MakeScopeExit([&]{ ftp::Counter::Upload().Stop(client.User().ID()); });  

  if (data.DataType() == ftp::DataType::ASCII && !cfg::Get().AsciiUploads().Allowed(path.ToString()))
  {
    control.Reply(ftp::ActionNotOkay, "File can't be uploaded in ASCII, change to BINARY.");
    throw cmd::NoPostScriptError();
  }
  
  fs::FileSinkPtr fout;
  try
  {
    if (data.RestartOffset() > 0)
      fout = fs::AppendFile(client.User(), path, data.RestartOffset());
    else
      fout = fs::CreateFile(client.User(), path);
  }
  catch (const util::SystemError& e)
  {
    if (data.RestartOffset() == 0 && e.Errno() == EEXIST)
    {
      DupeMessage(path);
    }
    else
    {
      std::ostringstream os;
      os << "Unable to " << (data.RestartOffset() > 0 ? "append" : "create")
         << " file: " << e.Message();
      control.Reply(ftp::ActionNotOkay, os.str());
    }
    throw cmd::NoPostScriptError();
  }
  catch (const util::RuntimeError& e)
  {
    std::ostringstream os;
    os << "Unable to " << (data.RestartOffset() > 0 ? "append" : "create")
       << " file: " << e.Message();
    control.Reply(ftp::ActionNotOkay, os.str());
    throw cmd::NoPostScriptError();
  }

  bool fileOkay = data.RestartOffset() > 0;
  auto fileGuard = util::MakeScopeExit([&]
  {
    if (!fileOkay)
    {
      try
      {
        fs::DeleteFile(fs::MakeReal(path));
      }
      catch (std::exception& e)
      {
        logs::Error("Failed to delete failed upload: %1%", e.what());
      }
    }
  });  
  
  std::stringstream os;
  os << "Opening " << (data.DataType() == ftp::DataType::ASCII ? "ASCII" : "BINARY") 
     << " connection for upload of " 
     << fs::MakePretty(path).ToString();
  if (data.Protection()) os << " using TLS/SSL";
  os << ".";
  control.Reply(ftp::TransferStatusOkay, os.str());
  
  try
  {
    data.Open(ftp::TransferType::Upload);
  }
  catch (const util::net::NetworkError&e )
  {
    if (!data.RestartOffset()) fs::DeleteFile(fs::MakeReal(path));
    control.Reply(ftp::CantOpenDataConnection,
                 "Unable to open data connection: " + e.Message());
    throw cmd::NoPostScriptError();
  }

  auto dataGuard = util::MakeScopeExit([&]
  {
    if (data.State().Type() != ftp::TransferType::None)
    {
      data.Close();
      if (data.State().Bytes() > 0)
      {
        db::stats::Upload(client.User(), data.State().Bytes() / 1024, 
                          data.State().Duration().total_milliseconds());
      }
    }
  });  
  
  if (!data.ProtectionOkay())
  {
    std::ostringstream os;
    os << "TLS is enforced on " << (data.IsFXP() ? "FXP" : "data") << " transfers.";
    control.Reply(ftp::ProtocolNotSupported, os.str());
    return;
  }

  auto section = cfg::Get().SectionMatch(path.ToString());
  
  auto transferLogGuard = util::MakeScopeExit([&]
  {
    if (cfg::Get().TransferLog().Uploads())
    {
      bool okay = !std::uncaught_exception();
      logs::Transfer(fs::MakeReal(path).ToString(), "up", client.User().Name(), client.User().PrimaryGroup(), 
                     (data.State().StartTime() - pt::ptime(gd::date(1970, 1, 1))).total_microseconds() / 1000000.0, 
                     data.State().Bytes() / 1024, data.State().Duration().total_microseconds() / 1000000.0,
                     okay, section ? section->Name() : std::string());
      }
  });
  
  const size_t bufferSize = cfg::Get().DataBufferSize();
  bool calcCrc = CalcCRC(path);
  std::unique_ptr<util::CRC32> crc32(cfg::Get().AsyncCRC() ? 
                                     new util::AsyncCRC32(bufferSize, 10) :
                                     new util::CRC32());
  bool aborted = false;
  fileOkay = false;
  
  try
  {
    ftp::UploadSpeedControl speedControl(client, path);
    ftp::OnlineTransferUpdater onlineUpdater(boost::this_thread::get_id(), stats::Direction::Upload,
                                             data.State().StartTime());
    std::vector<char> asciiBuffer;
    std::vector<char> buffer;
    buffer.resize(bufferSize);
    
    while (true)
    {
      size_t len = data.Read(&buffer[0], buffer.size());
      
      const char *bufp  = buffer.data();
      if (data.DataType() == ftp::DataType::ASCII)
      {
        ftp::ASCIITranscodeSTOR(bufp, len, asciiBuffer);
        len = asciiBuffer.size();
        bufp = asciiBuffer.data();
      }
      
      data.State().Update(len);
      
      fout->write(bufp, len);
      
      if (calcCrc) crc32->Update(reinterpret_cast<const uint8_t*>(bufp), len);
      onlineUpdater.Update(data.State().Bytes());
      speedControl.Apply();
    }
  }
  catch (const util::net::EndOfStream&) { }
  catch (const ftp::TransferAborted&) { aborted = true; }
  catch (const util::net::NetworkError& e)
  {
    control.Reply(ftp::DataCloseAborted,
                 "Error while reading from data connection: " + e.Message());
    throw cmd::NoPostScriptError();
  }
  catch (const std::ios_base::failure& e)
  {
    control.Reply(ftp::DataCloseAborted,
                  "Error while writing to disk: " + std::string(e.what()));
    throw cmd::NoPostScriptError();
  }
  catch (const ftp::ControlError& e)
  {
    e.Rethrow();
  }
  catch (const ftp::MinimumSpeedError& e)
  {
    logs::Debug("Aborted slow upload by %1%. %2% lower than %3%", 
                client.User().Name(),
                stats::AutoUnitSpeedString(e.Speed()),
                stats::AutoUnitSpeedString(e.Limit()));
    aborted = true;
  }

  fout->close();
  data.Close();
  
  e = fs::Chmod(fs::MakeReal(path), completeMode);
  if (!e) control.PartReply(ftp::DataClosedOkay, "Failed to chmod upload: " + e.Message());

  auto duration = data.State().Duration();
  double speed = stats::CalculateSpeed(data.State().Bytes(), duration);

  if (aborted)
  {
    control.Reply(ftp::DataClosedOkay, "Transfer aborted @ " + stats::AutoUnitSpeedString(speed / 1024)); 
    throw cmd::NoPostScriptError();
  }
  
  if (exec::PostCheck(client, path, 
                      calcCrc ? crc32->HexString() : "000000", speed, 
                      section ? section->Name() : ""))
  {
    fileOkay = true;
    bool nostats = !section || acl::path::FileAllowed<acl::path::Nostats>(client.User(), path);
    db::stats::Upload(client.User(), data.State().Bytes() / 1024,
                      duration.total_milliseconds(),
                      nostats ? "" : section->Name());    

    client.User().IncrSectionCredits(section && section->SeparateCredits() ? section->Name() : "", 
            data.State().Bytes() / 1024 * stats::UploadRatio(client.User(), path, section));
  }

  control.Reply(ftp::DataClosedOkay, "Transfer finished @ " + stats::AutoUnitSpeedString(speed / 1024)); 
  
  (void) countGuard;
  (void) fileGuard;
  (void) dataGuard;
}
Exemplo n.º 19
0
INT DBItemList::ParseResult(VOID* pResult, UINT& OldVersion, UINT& NowVersion)
{
	__ENTER_FUNCTION
	INT ret = 1;

	switch(mOPType) 
	{
	case DB_LOAD:
		{
			FULLUSERDATA* pCharFullData = static_cast<FULLUSERDATA*>(pResult);
			Assert(pCharFullData);
			enum 
			{
				DB_CharGuid	=	1,
				DB_ItemWorld,
				DB_ItemServer,
				DB_ItemGuid,
				DB_ItemType,
				DB_ItemPos,
				DB_FixAttr,  //也可以去掉,但是Login 需要读装备表
				DB_P1,
				DB_P2,
				DB_P3,
				DB_P4,
				DB_P5,
				DB_P6,
				DB_P7,
				DB_P8,
				DB_P9,
				DB_P10,
				DB_P11,
				DB_P12,
				DB_P13,
				DB_P14,
				DB_VERSION,
				DB_Creator,
				DB_Var,
			};

			Assert(mResultCount<=(DB_BANK_POS_END+1));

			Assert(mInterface);
			INT	   ErrorCode;

			//加载物品属性
			for(INT i =0;i<(DB_BANK_POS_END+1);i++)
			{
				if(!mInterface->Fetch())
					break;

				UINT	CharGuid = mInterface->GetUInt(DB_CharGuid,ErrorCode);
				USHORT	ItemPos  = mInterface->GetWORD(DB_ItemPos,ErrorCode);
				Assert(ItemPos<=DB_BANK_POS_END);

				_ITEM* pItem = pCharFullData->GetItem(ItemPos);

				Assert(pItem);

				pItem->m_ItemGUID.m_World	=	mInterface->GetBYTE(DB_ItemWorld,ErrorCode);
				pItem->m_ItemGUID.m_Server	=	mInterface->GetBYTE(DB_ItemServer,ErrorCode);
				pItem->m_ItemGUID.m_Serial	=	mInterface->GetUInt(DB_ItemGuid,ErrorCode);
				pItem->m_ItemIndex			=	mInterface->GetUInt(DB_ItemType,ErrorCode);
				
				CHAR FixAttr[MAX_FIX_ATTR_LENGTH];
				mInterface->GetField(DB_FixAttr,FixAttr,MAX_FIX_ATTR_LENGTH,ErrorCode);
				pItem->WriteFixAttr(FixAttr,MAX_FIX_ATTR_LENGTH);

				INT	PArray[14];
				PArray[0]		=	mInterface->GetInt(DB_P1,ErrorCode);
				PArray[1]		=	mInterface->GetInt(DB_P2,ErrorCode);
				PArray[2]		=	mInterface->GetInt(DB_P3,ErrorCode);
				PArray[3]		=	mInterface->GetInt(DB_P4,ErrorCode);
				PArray[4]		=	mInterface->GetInt(DB_P5,ErrorCode);
				PArray[5]		=	mInterface->GetInt(DB_P6,ErrorCode);
				PArray[6]		=	mInterface->GetInt(DB_P7,ErrorCode);
				PArray[7]		=	mInterface->GetInt(DB_P8,ErrorCode);
				PArray[8]		=	mInterface->GetInt(DB_P9,ErrorCode);
				PArray[9]		=	mInterface->GetInt(DB_P10,ErrorCode);
				PArray[10]		=	mInterface->GetInt(DB_P11,ErrorCode);
				PArray[11]		=	mInterface->GetInt(DB_P12,ErrorCode);
				PArray[12]		=	mInterface->GetInt(DB_P13,ErrorCode);
				PArray[13]		=	mInterface->GetInt(DB_P14,ErrorCode);
				OldVersion		=	mInterface->GetInt(DB_VERSION,ErrorCode);

				//序列化p1 ~ p12
				pItem->WriteVarAttr((CHAR*)PArray,sizeof(INT)*(DB_P14-DB_P1+1));
				mInterface->GetString(DB_Creator,pItem->m_Creator,MAX_ITEM_CREATOR_NAME,ErrorCode);
				mInterface->GetField(DB_Var,(CHAR*)pItem->m_Param,sizeof(INT)*MAX_ITEM_PARAM,ErrorCode);

				UINT dbVersion = CalcCRC((CHAR*)PArray);
				if( dbVersion & 0x80000000 && dbVersion != OldVersion )
				{
					NowVersion = dbVersion;
					ret = 2;
				}
			}
			mInterface->Clear();
		}
		break;
	case DB_DELETE:
		{
			Assert(mInterface);
			mInterface->Clear();	
		}
		break;
	default:
		break;
	}
	
	return ret;

	__LEAVE_FUNCTION

	return 0;
}
Exemplo n.º 20
0
int main(int argc, char **argv) {
  if (argc < 3) {
    PrintUsage(stderr, argv[0]);
    return -1;
  }

  if (!strcmp(argv[1], "create")) {
    if (argc < 4) {
      fprintf(stderr, "ERROR: incorrect create usage\n");
      return -2;
    }
    char *outbfile = argv[2];
    int n = atoi(argv[3]);

    /* Calculate btree size */
    int depth = CalcMinimumDepth(n);
    int sz = CalcTreeSize2(n, depth);
    fprintf(stderr, "n = %i, depth = %i, size = %i\n", n, depth, sz);

    /* Create memory buffer */
    mem = (char *) malloc(sz + 1);
    mem[sz] = 123; // Magic Marker to detect overflow
    memSize = sz;

    /* Init top node */
    BlockAddrT top = AllocBlock(0x0);
    Node topNode; 
    NodeInit(&topNode);
    topNode.depth = depth - 1; // total depth vs depth(rank?) of this node
    NodeSave(&topNode, top);
    BgTree tree;
    tree.topNode = top;

    /* Read in data */
    KeyT highestKey = 0;
    for (int i=0; i<n; i++) {
      KeyT key;
      BlockAddrT item;

      int res = fscanf(stdin, "%x\t%x", &key, &item);
      assert(res == 2);

      if (key < highestKey) {
        fprintf(stderr, "ERROR: Key out of order on line %i.  Input must be sorted!\n", i+1);
        return -3;
      }
      highestKey = key;
      //printf("GOT %i %i\n", key, item);
      TreeAppend(tree, key, item);
    }

    /* Set keys for non-leaf nodes */
    //NodeVisitDFS(&SetKeysVisitor, top);

    /* Write memory to file */
    assert(mem[sz] == 123);
    fprintf(stderr, "MEM: %i of %i allocated was used\n", memLast, memSize);
    FILE *f = fopen(outbfile, "wb");
    if (!f) {
      fprintf(stderr, "ERROR: Failed to open file %s for writing\n", outbfile);
      return -9;
    }
    int res = fwrite(mem, 1, memLast, f);
    if (res != memLast) {
      fprintf(stderr, "ERROR: Could not write all data to file %s\n", outbfile);
      return -4;
    }
    fclose(f);
  } // end of "create" command

  if (!strcmp(argv[1], "search")) {
    if (argc < 4) {
      fprintf(stderr, "ERROR: search usage incorrect, not enough arguments\n");
      return -11;
    }
    FILE *blobfile = 0x0;
    if (argc > 4) {
      blobfile = fopen(argv[4],"rb");
      if (!blobfile) {
        fprintf(stderr, "ERROR: failed to open Blob File %s\n", argv[4]);
        return -19;
      }
    }
    char *schema=0x0;
    if (argc > 5) {
      schema = argv[5];
    }

    char *inbfile = argv[2];
    KeyT key;
    int res;
    if (argv[3][0] == 'S') {
      key = CalcCRC(&argv[3][1], strlen(&argv[3][1]));
      //fprintf(stderr, "CRC32=%x for %s len=%i\n", key, &argv[3][1], (int) strlen(&argv[3][1]));
      printf("%x", key);
	if (mem)
    		free(mem);
	exit(0);
    } else { // assume hex
      res = sscanf(argv[3], "%x", &key);
      if (res != 1) {
        fprintf(stderr, "ERROR: Unable to parse query key argument %s\n", argv[3]);
        return -12;
      }
    }

    if (LoadBGT(inbfile) != 0) 
      return -99;

    /* Perform Search */
    BAT outParent;
    int outIndex;
    BAT found_temp;
    BAT found = FindInternal(0, key, &outParent, &outIndex);
    while (found != BAInvalid) {
	
//    if (found == BAInvalid) {
  //    printf("%x NOT FOUND!\n", key);
 //   } else {
      //printf("%x\t%08x", key, found);
      if (schema && blobfile) {
        for (char *p = &schema[0]; *p; ++p) {
          if ((*p == 's') || (*p == 'K')) {
            char buf[2000000];
            fseek(blobfile, found, SEEK_SET);
            int sz = UnpackStringFromFile(blobfile, buf, 2000000);
            if (sz < 0) {
              fprintf(stderr, "ERROR: Failed to read String from blob file\n");
              return -20;
            }
            found += sz;
            buf[sz] = 0x0; // not null terminated by default
            printf("\t%s", buf);

          } else if (*p == 'i') {
            int32_t v;
            fseek(blobfile, found, SEEK_SET);
            v = UnpackIntFromFile(blobfile);
            ERRORassert();
            found += 4;
            //printf("\t%i", v);
          } else if ((*p == 'I') || (*p == 'x') || (*p == 'X')) {
            uint32_t v;
            fseek(blobfile, found, SEEK_SET);
            v = UnpackUIntFromFile(blobfile);
            ERRORassert();
            //if (*p == 'I')
             // printf("\t%u", v);
            //else
             // printf("\t%x", v);
            found += 4;
          } else {
            fprintf(stderr, "ERROR: Unsupported schema character '%c'\n", *p);
            return -23;
          }

        }
      }
      printf("\n");
//	found_temp = NodeNextLeaf(NodeParent(found), found);
	//found_temp = FindInternal(0, key, &outParent, &outIndex);
	key++;
	found_temp = FindInternal(0, key, &outParent, &outIndex);
	found = found_temp;
	
    }
    if (blobfile)
      fclose(blobfile);
  } else if (!strcmp(argv[1],"printtree")) {
    if (LoadBGT(argv[2]) != 0) {
      printf("Error Loading BGT\n");
      return -99;
    }
    BgTree dummy;
    TreeInit(&dummy,0x0);
    NodeVisitDFS(dummy, &PrintVisitor, 0);
  }
  if (mem)
    free(mem);
}
Exemplo n.º 21
0
TEST(ErrorCheck, CalcCRC_NULL_NonZeroSize)
{
	TEST_ASSERT_EQUAL(0, CalcCRC(NULL, 10));
}
Exemplo n.º 22
0
INT		DBCharFullData::ParseResult(VOID* pResult, UINT& result1, UINT& result2, UINT& result3, UINT& result4)
{

	__ENTER_FUNCTION
	INT ret = 1;

	switch(mOPType)
	{
	case DB_LOAD:
		{

			FULLUSERDATA* pCharFullData = static_cast<FULLUSERDATA*>(pResult);
			Assert(pCharFullData);

			pCharFullData->CleanUp();
			enum 
			{
				DB_CharGuid	=	1,
				DB_CharName,
				DB_Title,
				DB_Sex,
				DB_CreateTime,
				DB_Level,
				DB_Enegry,
				DB_Exp,
				DB_Money,
				DB_Pw,
				DB_HairColor,
				DB_FaceColor,
				DB_HairModel,
				DB_FaceModel,
				DB_Scene,
				DB_XPos,
				DB_ZPos,
				DB_LoginTime,
				DB_LogoutTime,
				DB_Version,
				DB_Camp,
				DB_Menpai,
				DB_HP,
				DB_MP,
				DB_StrikePoint,
				DB_Str,
				DB_Spr,
				DB_Con,
				DB_Ipr,
				DB_Dex,
				DB_Points,
				DB_Setting,
				DB_ShopInfo,
				DB_CarryPet,
				DB_GuildID,
				DB_TeamID,
				DB_HeadID,
				DB_eRecover,
				DB_RMB,
				DB_BANKRMB,
				DB_VRecover,
				DB_EnergyMax,
				DB_PwdelTime,
				DB_DieTime,
				DB_BankMoney,
				DB_BankEnd,
				DB_BackScene,
				DB_BackXPos,
				DB_BackZPos,
				DB_Rage,
			};
			
			Assert(mResultCount<=1);
			Assert(mInterface);
			INT	   ErrorCode;

			//加载基本属性
			for(INT i =0;i<1;i++)
			{
				if(!mInterface->Fetch())
					break;

				//加载角色基本属性
				pCharFullData->m_Human.m_GUID	=	mInterface->GetUInt(DB_CharGuid,ErrorCode);
				mInterface->GetString(DB_CharName,pCharFullData->m_Human.m_Name,MAX_CHARACTER_NAME,ErrorCode);
				mInterface->GetString(DB_Title,pCharFullData->m_Human.m_Title,MAX_CHARACTER_TITLE,ErrorCode);
				pCharFullData->m_Human.m_Sex	=	mInterface->GetUInt(DB_Sex,ErrorCode);
				pCharFullData->m_Human.m_CreateDate	=	mInterface->GetUInt(DB_CreateTime,ErrorCode);
				pCharFullData->m_Human.m_Level	=	mInterface->GetUInt(DB_Level,ErrorCode);
				pCharFullData->m_Human.m_DoubleExpTime_Num	=	mInterface->GetUInt(DB_Enegry,ErrorCode);
				pCharFullData->m_Human.m_Exp	=	mInterface->GetUInt(DB_Exp,ErrorCode);
				pCharFullData->m_Human.m_Money	=	mInterface->GetUInt(DB_Money,ErrorCode);

				mInterface->GetString(DB_Pw,pCharFullData->m_Human.m_Passwd,MAX_PWD,ErrorCode);
				pCharFullData->m_Human.m_HairColor	=	mInterface->GetUInt(DB_HairColor,ErrorCode);
				pCharFullData->m_Human.m_FaceColor	=	mInterface->GetBYTE(DB_FaceColor,ErrorCode);
				pCharFullData->m_Human.m_HairModel	=	mInterface->GetBYTE(DB_HairModel,ErrorCode);
				pCharFullData->m_Human.m_FaceModel	=	mInterface->GetBYTE(DB_FaceModel,ErrorCode);
				pCharFullData->m_Human.m_StartScene		=	mInterface->GetUInt(DB_Scene,ErrorCode);
				pCharFullData->m_Human.m_Position.m_fX	=	mInterface->GetUInt(DB_XPos,ErrorCode)*0.01f;
				pCharFullData->m_Human.m_Position.m_fZ	=	mInterface->GetUInt(DB_ZPos,ErrorCode)*0.01f;
				pCharFullData->m_Human.m_LastLoginTime	=	mInterface->GetUInt(DB_LoginTime,ErrorCode);
				pCharFullData->m_Human.m_LastLogoutTime	=	mInterface->GetUInt(DB_LogoutTime,ErrorCode);
				pCharFullData->m_Human.m_DBVersion		=	mInterface->GetUInt(DB_Version,ErrorCode);
				mInterface->GetField(DB_Camp,
									  (CHAR*)(&pCharFullData->m_Human.m_CampData),
									   sizeof(_CAMP_DATA),
									   ErrorCode);

				pCharFullData->m_Human.m_MenPai	=	mInterface->GetUInt(DB_Menpai,ErrorCode);
				pCharFullData->m_Human.m_HP	=	mInterface->GetUInt(DB_HP,ErrorCode);
				pCharFullData->m_Human.m_MP	=	mInterface->GetUInt(DB_MP,ErrorCode);
				pCharFullData->m_Human.m_StrikePoint	=	mInterface->GetUInt(DB_StrikePoint,ErrorCode);
				pCharFullData->m_Human.m_BaseAttrLevel1.m_pAttr[CATTR_LEVEL1_STR]	=	mInterface->GetUInt(DB_Str,ErrorCode);
				pCharFullData->m_Human.m_BaseAttrLevel1.m_pAttr[CATTR_LEVEL1_SPR]	=	mInterface->GetUInt(DB_Spr,ErrorCode);
				pCharFullData->m_Human.m_BaseAttrLevel1.m_pAttr[CATTR_LEVEL1_CON]	=	mInterface->GetUInt(DB_Con,ErrorCode);
				pCharFullData->m_Human.m_BaseAttrLevel1.m_pAttr[CATTR_LEVEL1_INT]	=	mInterface->GetUInt(DB_Ipr,ErrorCode);
				pCharFullData->m_Human.m_BaseAttrLevel1.m_pAttr[CATTR_LEVEL1_DEX]	=	mInterface->GetUInt(DB_Dex,ErrorCode);
				pCharFullData->m_Human.m_Level1Points	=	mInterface->GetUInt(DB_Points,ErrorCode);
				mInterface->GetField(DB_Setting,
									  (CHAR*)&pCharFullData->m_Setting,
									  sizeof(_SETTING_DB_LOAD),
									  ErrorCode);
				
				_HUMAN_DB_LOAD::_PSHOP_INFO	ShopInfo;
				mInterface->GetField(DB_ShopInfo,
									  (CHAR*)&ShopInfo,
									  sizeof(ShopInfo),
									  ErrorCode);

				memcpy(pCharFullData->m_Human.m_ShopGuid,ShopInfo.m_ShopGuid,sizeof(_PLAYERSHOP_GUID)*MAX_SHOP_NUM_PER_PLAYER);
				memcpy(pCharFullData->m_Human.m_FavoriteList,ShopInfo.m_FavoriteList,sizeof(_PLAYERSHOP_GUID)*MAX_FAVORITE_SHOPS);

				mInterface->GetField(DB_CarryPet,
									  (CHAR*)&pCharFullData->m_Human.m_guidCurrentPet,
									  sizeof(PET_GUID_t),
									  ErrorCode);
				
				pCharFullData->m_Human.m_GuildID	=	mInterface->GetUInt(DB_GuildID,ErrorCode);
				pCharFullData->m_Human.m_TeamID		=	mInterface->GetUInt(DB_TeamID,ErrorCode);
				pCharFullData->m_Human.m_PortraitID	=	mInterface->GetUInt(DB_HeadID,ErrorCode);
				pCharFullData->m_Human.m_EnergyRegeneRate	=	mInterface->GetInt(DB_eRecover,ErrorCode);	
				pCharFullData->m_Human.m_RMBMoney				=	mInterface->GetInt(DB_RMB,ErrorCode);					
				pCharFullData->m_Human.m_BankRMB			=  mInterface->GetInt(DB_BANKRMB,ErrorCode);
				pCharFullData->m_Human.m_VigorRegeneRate	=	mInterface->GetInt(DB_VRecover,ErrorCode);
				pCharFullData->m_Human.m_GmRight	=	mInterface->GetInt(DB_EnergyMax,ErrorCode);
				pCharFullData->m_Human.m_uPwdDelTime	=	mInterface->GetUInt(DB_PwdelTime,ErrorCode);
				pCharFullData->m_Human.m_LeftDieTime	=	mInterface->GetUInt(DB_DieTime,ErrorCode);
				pCharFullData->m_Bank.m_Money	=	mInterface->GetUInt(DB_BankMoney,ErrorCode);
				pCharFullData->m_Bank.m_CurEndIndex	=	mInterface->GetUInt(DB_BankEnd,ErrorCode);
				pCharFullData->m_Human.m_BakScene	=	mInterface->GetUInt(DB_BackScene,ErrorCode);
				pCharFullData->m_Human.m_BakPosition.m_fX = mInterface->GetUInt(DB_BackXPos,ErrorCode)*0.01f;
				pCharFullData->m_Human.m_BakPosition.m_fZ = mInterface->GetUInt(DB_BackZPos,ErrorCode)*0.01f;
				pCharFullData->m_Human.m_Rage			  = mInterface->GetUInt(DB_Rage,ErrorCode);

				mInterface->Clear();

				UINT dbVersion = CalcCRC( pCharFullData );
				if( dbVersion & 0x80000000 && dbVersion != pCharFullData->m_Human.m_DBVersion )
				{
					result1 = pCharFullData->m_Human.m_DBVersion;
					result2 = dbVersion;
					ret = 2;
				}

				dbVersion = 0;
				
				//加载装备
				DBItemList	ItemListObject(mInterface);
				ItemListObject.SetCharGuid(m_CharGuid);
				ItemListObject.SetDBVersion(dbVersion);
				if(!ItemListObject.Load())
					return FALSE;

				INT nItemRet = ItemListObject.ParseResult(pCharFullData,result3,result4);
				if( nItemRet == 2 )
				{
					ret = 3;
				}

				//加载技能
				DBSkillList	SkillListObject(mInterface);
				SkillListObject.SetCharGuid(m_CharGuid);
				SkillListObject.SetDBVersion(dbVersion);
				if(!SkillListObject.Load())
					return FALSE;
				SkillListObject.ParseResult(pCharFullData);

				//加载心法
				DBXinFaList	XinFaListObject(mInterface);
				XinFaListObject.SetCharGuid(m_CharGuid);
				XinFaListObject.SetDBVersion(dbVersion);
				if(!XinFaListObject.Load())
					return FALSE;
				XinFaListObject.ParseResult(pCharFullData);

				//加载生活技能
				DBAbilityList AbilityListObject(mInterface);
				AbilityListObject.SetCharGuid(m_CharGuid);
				AbilityListObject.SetDBVersion(dbVersion);
				if(!AbilityListObject.Load())
					return FALSE;
				AbilityListObject.ParseResult(pCharFullData);

				//加载任务信息
				DBTaskList	TaskListObject(mInterface);
				TaskListObject.SetCharGuid(m_CharGuid);
				TaskListObject.SetDBVersion(dbVersion);
				if(!TaskListObject.Load())
					return FALSE;

				TaskListObject.ParseResult(pCharFullData);

				//加载关系列表
				DBRelationList	RelationListObject(mInterface);
				RelationListObject.SetCharGuid(m_CharGuid);
				RelationListObject.SetDBVersion(dbVersion);
				if(!RelationListObject.Load())
					return FALSE;
				RelationListObject.ParseResult(pCharFullData);

				//Impact 列表
				DBImpactList	ImpactListObject(mInterface);
				ImpactListObject.SetCharGuid(m_CharGuid);
				ImpactListObject.SetDBVersion(dbVersion);
				if(!ImpactListObject.Load())
					return FALSE;
				ImpactListObject.ParseResult(pCharFullData);
				//宠物
				DBPetList	PetListObject(mInterface);
				PetListObject.SetCharGuid(m_CharGuid);
				PetListObject.SetDBVersion(dbVersion);
				if(!PetListObject.Load())
					return FALSE;
				PetListObject.ParseResult(pCharFullData);
				
				DBPrivateInfo PrivateInfoObject(mInterface);
				PrivateInfoObject.SetCharGuid(m_CharGuid);
				PrivateInfoObject.SetDBVersion(dbVersion);
				if(!PrivateInfoObject.Load())
					return FALSE;
				PrivateInfoObject.ParseResult(pCharFullData);

				DBTitleInfo	TitleInfoObject(mInterface);
				TitleInfoObject.SetCharGuid(m_CharGuid);
				TitleInfoObject.SetDBVersion(dbVersion);
				if(!TitleInfoObject.Load())
					return FALSE;
				TitleInfoObject.ParseResult(pCharFullData);

				DBCoolDownInfo	CoolDownInfoObject(mInterface);
				CoolDownInfoObject.SetCharGuid(m_CharGuid);
				CoolDownInfoObject.SetDBVersion(dbVersion);
				if(!CoolDownInfoObject.Load())
					return FALSE;
				CoolDownInfoObject.ParseResult(pCharFullData);
		
				//DBWebShopInfo	WebShopInfo(mInterface);
				//WebShopInfo.SetCharGuid(m_CharGuid);
				//WebShopInfo.SetDBVersion(dbVersion);
				//WebShopInfo.SetIsSucceed(FALSE);
				//if(!WebShopInfo.Load())
				//	return FALSE;
				//WebShopInfo.ParseResult(pCharFullData);
			}
		}
		break;
	case DB_SAVE:
		{
			
		}
		break;
	default:
		break;
	}


	return ret;

	__LEAVE_FUNCTION

	return FALSE;
}
Exemplo n.º 23
0
BOOL DBCharFullData::Save(VOID* pSource)
{

	__ENTER_FUNCTION

	DB_QUERY* pQuery = GetInternalQuery();

	if(!pQuery)
	{
		Assert(FALSE);
	}

	pQuery->Clear();

	if(m_CharGuid==INVALID_ID)
	{
		return FALSE;
	}

	FULLUSERDATA* pCharFullData = static_cast<FULLUSERDATA*>(pSource);
	Assert(pCharFullData);
	


	if(!StrSafeCheck(pCharFullData->m_Human.m_Title,MAX_CHARACTER_TITLE))
		return FALSE;
	if(!StrSafeCheck(pCharFullData->m_Human.m_Passwd,MAX_PWD))
		return FALSE;
	

	CHAR CharCamp[100];
	memset(CharCamp,0,100);
	Binary2String((CHAR*)(&pCharFullData->m_Human.m_CampData),
				   sizeof(_CAMP_DATA),
				   CharCamp);

	CHAR CharSetting[2048];
	memset(CharSetting,0,2048);
	Binary2String((CHAR*)(&pCharFullData->m_Setting),
				   sizeof(_SETTING_DB_LOAD),
		           CharSetting);
	CHAR CharShopInfo[512];
	memset(CharShopInfo,0,512);


	_HUMAN_DB_LOAD::_PSHOP_INFO	ShopInfo;
	memcpy(ShopInfo.m_ShopGuid,pCharFullData->m_Human.m_ShopGuid,sizeof(_PLAYERSHOP_GUID)*MAX_SHOP_NUM_PER_PLAYER);
	memcpy(ShopInfo.m_FavoriteList,pCharFullData->m_Human.m_FavoriteList,sizeof(_PLAYERSHOP_GUID)*MAX_FAVORITE_SHOPS);

	Binary2String((CHAR*)&ShopInfo,
				 sizeof(ShopInfo),
				 CharShopInfo);

	CHAR CharCarryPet[100];
	memset(CharCarryPet,0,100);
	Binary2String((CHAR*)&pCharFullData->m_Human.m_guidCurrentPet,
				  sizeof(PET_GUID_t),
				 CharCarryPet);

	UINT dbVersion = CalcCRC(pSource);

	pQuery->Parse(UpdateCharFullData,
				  CHAR_TABLE,
				  pCharFullData->m_Human.m_Title,
				  pCharFullData->m_Human.m_Sex,
				  pCharFullData->m_Human.m_Level,
				  pCharFullData->m_Human.m_DoubleExpTime_Num,
				  pCharFullData->m_Human.m_Exp,
				  pCharFullData->m_Human.m_Money,
				  pCharFullData->m_Human.m_Passwd,
				  pCharFullData->m_Human.m_HairColor,
				  pCharFullData->m_Human.m_FaceColor,
				  pCharFullData->m_Human.m_HairModel,
				  pCharFullData->m_Human.m_FaceModel,
				  pCharFullData->m_Human.m_StartScene,
				  Float2Int(pCharFullData->m_Human.m_Position.m_fX*100),
				  Float2Int(pCharFullData->m_Human.m_Position.m_fZ*100),
				  pCharFullData->m_Human.m_LastLoginTime,
				  pCharFullData->m_Human.m_LastLogoutTime,
				  //pCharFullData->m_Human.m_DBVersion,
				  CharCamp,
				  pCharFullData->m_Human.m_MenPai,
				  pCharFullData->m_Human.m_HP,
				  pCharFullData->m_Human.m_MP,
				  pCharFullData->m_Human.m_StrikePoint,
				  pCharFullData->m_Human.m_BaseAttrLevel1.m_pAttr[CATTR_LEVEL1_STR],
				  pCharFullData->m_Human.m_BaseAttrLevel1.m_pAttr[CATTR_LEVEL1_SPR],
				  pCharFullData->m_Human.m_BaseAttrLevel1.m_pAttr[CATTR_LEVEL1_CON],
				  pCharFullData->m_Human.m_BaseAttrLevel1.m_pAttr[CATTR_LEVEL1_INT],
				  pCharFullData->m_Human.m_BaseAttrLevel1.m_pAttr[CATTR_LEVEL1_DEX],
				  pCharFullData->m_Human.m_Level1Points,
				  CharSetting,
				  CharShopInfo,
				  CharCarryPet,
				  pCharFullData->m_Human.m_GuildID,
				  pCharFullData->m_Human.m_TeamID,
				  pCharFullData->m_Human.m_PortraitID,
				  pCharFullData->m_Human.m_EnergyRegeneRate,
				  pCharFullData->m_Human.m_RMBMoney,
				  pCharFullData->m_Human.m_BankRMB,
				  pCharFullData->m_Human.m_VigorRegeneRate,
				  pCharFullData->m_Human.m_GmRight,
				  pCharFullData->m_Human.m_uPwdDelTime,
				  pCharFullData->m_Human.m_LeftDieTime,
				  pCharFullData->m_Bank.m_Money,
				  pCharFullData->m_Bank.m_CurEndIndex,
				  pCharFullData->m_Human.m_BakScene,
				  Float2Int(pCharFullData->m_Human.m_BakPosition.m_fX*100),
				  Float2Int(pCharFullData->m_Human.m_BakPosition.m_fZ*100),
				  pCharFullData->m_Human.m_Rage,
				  dbVersion,
				  m_CharGuid);
	
	if(!ODBCBase::Save(pSource))
		return FALSE;
	

	Assert(mResultCount<=1);
	mInterface->Clear();
	if(mResultCount==0)
	{
		return TRUE;
	}
	
	dbVersion = 0;

	//保存装备
	DBItemList	ItemListObject(mInterface);
	ItemListObject.SetCharGuid(m_CharGuid);
	ItemListObject.SetDBVersion(dbVersion);
	if(!ItemListObject.Save(pCharFullData))
		return FALSE;
	ItemListObject.ParseResult(pCharFullData);

	//保存技能
	DBSkillList	SkillListObject(mInterface);
	SkillListObject.SetCharGuid(m_CharGuid);
	SkillListObject.SetDBVersion(dbVersion);
	if(!SkillListObject.Save(pCharFullData))
		return FALSE;
	SkillListObject.ParseResult(pCharFullData);

	//保存心法
	DBXinFaList	XinFaListObject(mInterface);
	XinFaListObject.SetCharGuid(m_CharGuid);
	XinFaListObject.SetDBVersion(dbVersion);
	if(!XinFaListObject.Save(pCharFullData))
		return FALSE;
	XinFaListObject.ParseResult(pCharFullData);

	//保存生活技能
	DBAbilityList AbilityListObject(mInterface);
	AbilityListObject.SetCharGuid(m_CharGuid);
	AbilityListObject.SetDBVersion(dbVersion);
	if(!AbilityListObject.Save(pCharFullData))
		return FALSE;
	AbilityListObject.ParseResult(pCharFullData);

	//保存任务信息
	DBTaskList	TaskListObject(mInterface);
	TaskListObject.SetCharGuid(m_CharGuid);
	TaskListObject.SetDBVersion(dbVersion);
	if(!TaskListObject.Save(pCharFullData))
		return FALSE;
	TaskListObject.ParseResult(pCharFullData);

	//保存关系列表
	DBRelationList	RelationListObject(mInterface);
	RelationListObject.SetCharGuid(m_CharGuid);
	RelationListObject.SetDBVersion(dbVersion);
	if(!RelationListObject.Save(pCharFullData))
		return FALSE;
	RelationListObject.ParseResult(pCharFullData);

	//保存Impact 列表
	DBImpactList	ImpactListObject(mInterface);
	ImpactListObject.SetCharGuid(m_CharGuid);
	ImpactListObject.SetDBVersion(dbVersion);
	if(!ImpactListObject.Save(pCharFullData))
		return FALSE;
	ImpactListObject.ParseResult(pCharFullData);
	//保存宠物	列表
	DBPetList	PetListObject(mInterface);
	PetListObject.SetCharGuid(m_CharGuid);
	PetListObject.SetDBVersion(dbVersion);
	if(!PetListObject.Save(pCharFullData))
		return FALSE;
	PetListObject.ParseResult(pCharFullData);
	//私人信息
	DBPrivateInfo	PrivateInfoObject(mInterface);
	PrivateInfoObject.SetCharGuid(m_CharGuid);
	PrivateInfoObject.SetDBVersion(dbVersion);
	if(!PrivateInfoObject.Save(pCharFullData))
		return FALSE;
	PrivateInfoObject.ParseResult(pCharFullData);
	//称号信息
	DBTitleInfo		TitleInfoObject(mInterface);
	TitleInfoObject.SetCharGuid(m_CharGuid);
	TitleInfoObject.SetDBVersion(dbVersion);
	if(!TitleInfoObject.Save(pCharFullData))
		return FALSE;
	TitleInfoObject.ParseResult(pCharFullData);

	//冷却信息
	DBCoolDownInfo		CoolDownInfoObject(mInterface);
	CoolDownInfoObject.SetCharGuid(m_CharGuid);
	CoolDownInfoObject.SetDBVersion(dbVersion);
	if(!CoolDownInfoObject.Save(pCharFullData))
		return FALSE;
	CoolDownInfoObject.ParseResult(pCharFullData);

	//商店信息
	//DBWebShopInfo		WebShopInfo(mInterface);
	//WebShopInfo.SetCharGuid(m_CharGuid);
	//WebShopInfo.SetDBVersion(dbVersion);
	//WebShopInfo.SetWebShopInfoId(pCharFullData->m_PrivateInfo.pi.wsInfo[0].Id);
	//if(!WebShopInfo.Save(pCharFullData))
	//	return FALSE;
	//WebShopInfo.ParseResult(pCharFullData);

	return TRUE;

	__LEAVE_FUNCTION

	return FALSE;
}
Exemplo n.º 24
0
// read caps chunk
int CCapsLoader::ReadChunk(int idbrk)
{
	// handle file error
	if (!file.IsOpen())
		return ccidErrFile;

	// skip data area if any
	SkipData();

	// check EOF
	int pos=file.GetPosition();
	if (pos == flen)
		return ccidEof;

	// check for ID chunk size
	if (flen-pos < sizeof(CapsID))
		return ccidErrShort;

	// read ID chunk
	if (file.Read((PUBYTE)&xchunk.file, sizeof(CapsID)) != sizeof(CapsID))
		return ccidErrShort;
	chunk.cg.file=xchunk.file;

	// identify chunk type if possible
	int type=GetChunkType(&chunk);

	// stop if break on unknown types
	if (idbrk && type==ccidUnknown)
		return ccidUnknown;

	// set ID to host format
	Swap(PUDWORD((PUBYTE)&chunk.cg.file+sizeof(chunk.cg.file.name)), sizeof(CapsID)-sizeof(chunk.cg.file.name));

	// load modifier for known chunk types, skip for unknown types
	int modsize=chunk.cg.file.size-sizeof(CapsID);
	if (modsize > 0) {
		// check for valid modifier size
		pos=file.GetPosition();
		if (flen-pos < modsize)
			return ccidErrShort;

		// read mod chunk if buffer has enough space or skip it
		if (modsize <= sizeof(CapsMod)) {
			// read mod chunk
			if (file.Read((PUBYTE)&xchunk.mod, modsize) != modsize)
				return ccidErrShort;

			// set header to host format
			chunk.cg.mod=xchunk.mod;
			Swap(PUDWORD((PUBYTE)&chunk.cg.mod), modsize);
		} else {
			// seek to new chunk
			file.Seek(modsize, 0);
		}
	}

	// check CRC value for completely read headers
	if (modsize>=0 && modsize<=sizeof(CapsMod)) {
		xchunk.file.hcrc=0;
		if (chunk.cg.file.hcrc != CalcCRC((PUBYTE)&xchunk.file, chunk.cg.file.size))
			return ccidErrHeader;
	}

	return type;
}
Exemplo n.º 25
0
//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
bool CTFStatPanel::ReadStats( void )
{
	CDmxElement *pPlayerStats;

	DECLARE_DMX_CONTEXT();

	if ( IsX360() )
	{
#ifdef _X360
		if ( XBX_GetStorageDeviceId() == XBX_INVALID_STORAGE_ID || XBX_GetStorageDeviceId() == XBX_STORAGE_DECLINED )
			return false;
#endif
	}

	char	szFilename[_MAX_PATH];

	if ( IsX360() )
	{
		Q_snprintf( szFilename, sizeof( szFilename ), "cfg:/tf2_playerstats.dmx" );
	}
	else
	{
		Q_snprintf( szFilename, sizeof( szFilename ), "tf2_playerstats.dmx" );
	}

	MEM_ALLOC_CREDIT();

	bool bOk = UnserializeDMX( szFilename, "MOD", true, &pPlayerStats );

	if ( !bOk )
		return false;

	int iVersion = pPlayerStats->GetValue< int >( "iVersion" );
	if ( iVersion > PLAYERSTATS_FILE_VERSION )
	{
		// file is beyond our comprehension
		return false;
	}

	int iSteamID = pPlayerStats->GetValue<int>( "SteamID" );
	int iCRCFile = pPlayerStats->GetValue<int>( "iTimestamp" );	
	
	const CUtlVector< CDmxElement* > &aClassStatsList = pPlayerStats->GetArray< CDmxElement * >( "aClassStats" );
	int iCount = aClassStatsList.Count();
	m_aClassStats.SetCount( iCount );
	for( int i = 0; i < m_aClassStats.Count(); i++ )
	{
		CDmxElement *pClass = aClassStatsList[ i ];
		ClassStats_t &stat = m_aClassStats[ i ];

		pClass->UnpackIntoStructure( &stat, s_ClassStatsUnpack );

		CDmxElement *pAccumulated = pClass->GetValue< CDmxElement * >( "accumulated" );
		pAccumulated->UnpackIntoStructure( &stat.accumulated, s_RoundStatsUnpack );

		CDmxElement *pMax = pClass->GetValue< CDmxElement * >( "max" );
		pMax->UnpackIntoStructure( &stat.max, s_RoundStatsUnpack );
	}

	CleanupDMX( pPlayerStats );

	UpdateStatSummaryPanel();

	// check file CRC and steam ID to see if we think this file has not been tampered with
	int iCRC = CalcCRC( iSteamID );
	// does file CRC match CRC generated from file data, and is there a Steam ID in the file
	if ( ( iCRC == iCRCFile ) && ( iSteamID > 0 ) && SteamUser() ) 
	{		
		// does the file Steam ID match current Steam ID (so you can't hand around files)
		CSteamID steamID = SteamUser()->GetSteamID();
		if ( steamID.GetAccountID() == (uint32) iSteamID )
		{
			m_bLocalFileTrusted = true;
		}
	}

	m_bStatsChanged = false;

	return true;
}