bool CNetAddr::SetSpecial(const std::string &strName)
{
    if (strName.size()>6 && strName.substr(strName.size() - 6, 6) == ".onion") {
        std::vector<unsigned char> vchAddr = DecodeBase32(strName.substr(0, strName.size() - 6).c_str());
        if (vchAddr.size() != 16-sizeof(pchOnionCat))
            return false;
        memcpy(ip, pchOnionCat, sizeof(pchOnionCat));
        for (unsigned int i=0; i<16-sizeof(pchOnionCat); i++)
            ip[i + sizeof(pchOnionCat)] = vchAddr[i];
        return true;
    }
    return false;
}
예제 #2
0
/** \brief We sometimes have a vast reservoir of i2p destinations, b32.i2p addresses are simply the hash
of those addresses, so we should be able to look them up here, if we already have the base64 string,
we're done and never have to ask the router to lookup the destination.
 *
 * \param sB32addr const string&
 * \return CAddrInfo*
 *
 */
CAddrInfo* CAddrMan::LookupB32addr(const std::string& sB32addr)
{
    // Convert the string back into a hash, and look it up in the AddrMan map
    if( isValidI2pB32(sB32addr) ) {
        bool fValid;
        std::vector<unsigned char> vchHash;
        std::string sHash = sB32addr;
        sHash.resize( sB32addr.size() - 8 );
        vchHash = DecodeBase32( sHash.c_str(), &fValid );
        uint256 uintHash( vchHash );        // Hate wasting time copying object, but vectors, strings and uint256 values dont always pass compiler checks otherwise
        if( fValid ) {                      // Lookup the hash for a match, if found we have the CAddrInfo id
            std::map<uint256, int>::iterator it = mapI2pHashes.find( uintHash );
            if( it != mapI2pHashes.end() ) {
                std::map<int, CAddrInfo>::iterator it2 = mapInfo.find((*it).second);
                if (it2 != mapInfo.end())
                    return &(*it2).second;
            }
        }
    }
    return NULL;
}
예제 #3
0
void TestSerialFormatStuff()
{
	for (int ii = 0; ii < 256; ++ii)
	{
		OVR_ASSERT(Base32FromChar[ii] == (char)DecodeBase32((char)ii));
	}

	DK2BinarySerialFormat sa;
	sa.ProductId = DK2ProductId_DK2;
	sa.PartId = DK2PartId_HMD;
	sa.MinutesSinceEpoch = 65000;
	sa.UnitNumber = 2;
	sa.MacHash[0] = 0xa1;
	sa.MacHash[1] = 0xb2;
	sa.MacHash[2] = 0xc3;
	sa.MacHash[3] = 0xd4;
	sa.MacHash[4] = 0xe5;

	uint8_t buffer[12];
	sa.ToBuffer(buffer);

	DK2BinarySerialFormat sb;
	OVR_ASSERT(sb.FromBuffer(buffer));

	OVR_ASSERT(sa == sb);

	DK2PrintedSerialFormat psn;
	psn.FromBinary(sb);

	OVR_ASSERT(psn == sa);

	String s = psn.ToBase32();

	DK2PrintedSerialFormat psn2;
	psn2.FromBase32(s.ToCStr());

	OVR_ASSERT(psn == psn2);
}
std::string DecodeBase32(const std::string& str)
{
    std::vector<unsigned char> vchRet = DecodeBase32(str.c_str());
    return std::string((const char*)vchRet.data(), vchRet.size());
}
예제 #5
0
파일: ED2KLink.cpp 프로젝트: machado2/emule
/////////////////////////////////////////////
// CED2KFileLink implementation
/////////////////////////////////////////////
CED2KFileLink::CED2KFileLink(const TCHAR* pszName, const TCHAR* pszSize, const TCHAR* pszHash, 
							 const CStringArray& astrParams, const TCHAR* pszSources)
	: m_size(pszSize)
{
	// Here we have a little problem.. Actually the proper solution would be to decode from UTF8,
	// only if the string does contain escape sequences. But if user pastes a raw UTF8 encoded
	// string (for whatever reason), we would miss to decode that string. On the other side, 
	// always decoding UTF8 can give flaws in case the string is valid for Unicode and UTF8
	// at the same time. However, to avoid the pasting of raw UTF8 strings (which would lead
	// to a greater mess in the network) we always try to decode from UTF8, even if the string
	// did not contain escape sequences.
	m_name = OptUtf8ToStr(URLDecode(pszName));
	m_name.Trim();
	if (m_name.IsEmpty())
		throw GetResString(IDS_ERR_NOTAFILELINK);

	SourcesList = NULL;
	m_hashset = NULL;
	m_bAICHHashValid = false;

	if (_tcslen(pszHash) != 32)
		throw GetResString(IDS_ERR_ILLFORMEDHASH);

	if (_tstoi64(pszSize)>=4294967295)
		throw GetResString(IDS_ERR_TOOLARGEFILE);
	if (_tstoi64(pszSize)<=0)
		throw GetResString(IDS_ERR_NOTAFILELINK);
	
	for (int idx = 0; idx < 16; ++idx) {
		m_hash[idx] = FromHexDigit(*pszHash++)*16;
		m_hash[idx] += FromHexDigit(*pszHash++);
	}

	bool bError = false;
	for (int i = 0; !bError && i < astrParams.GetCount(); i++)
	{
		const CString& strParam = astrParams.GetAt(i);
		ASSERT( !strParam.IsEmpty() );

		CString strTok;
		int iPos = strParam.Find(_T('='));
		if (iPos != -1)
			strTok = strParam.Left(iPos);
		if (strTok == _T("s"))
		{
			CString strURL = strParam.Mid(iPos + 1);
			if (!strURL.IsEmpty())
			{
				TCHAR szScheme[INTERNET_MAX_SCHEME_LENGTH];
				TCHAR szHostName[INTERNET_MAX_HOST_NAME_LENGTH];
				TCHAR szUrlPath[INTERNET_MAX_PATH_LENGTH];
				TCHAR szUserName[INTERNET_MAX_USER_NAME_LENGTH];
				TCHAR szPassword[INTERNET_MAX_PASSWORD_LENGTH];
				TCHAR szExtraInfo[INTERNET_MAX_URL_LENGTH];
				URL_COMPONENTS Url = {0};
				Url.dwStructSize = sizeof(Url);
				Url.lpszScheme = szScheme;
				Url.dwSchemeLength = ARRSIZE(szScheme);
				Url.lpszHostName = szHostName;
				Url.dwHostNameLength = ARRSIZE(szHostName);
				Url.lpszUserName = szUserName;
				Url.dwUserNameLength = ARRSIZE(szUserName);
				Url.lpszPassword = szPassword;
				Url.dwPasswordLength = ARRSIZE(szPassword);
				Url.lpszUrlPath = szUrlPath;
				Url.dwUrlPathLength = ARRSIZE(szUrlPath);
				Url.lpszExtraInfo = szExtraInfo;
				Url.dwExtraInfoLength = ARRSIZE(szExtraInfo);
				if (InternetCrackUrl(strURL, 0, 0, &Url) && Url.dwHostNameLength > 0)
				{
					SUnresolvedHostname* hostname = new SUnresolvedHostname;
					hostname->strURL = strURL;
					hostname->strHostname = szHostName;
					m_HostnameSourcesList.AddTail(hostname);
				}
			}
			else
				ASSERT(0);
		}
		else if (strTok == _T("p"))
		{
			CString strPartHashs = strParam.Tokenize(_T("="), iPos);

			if (m_hashset != NULL){
				ASSERT(0);
				bError = true;
				break;
			}

			m_hashset = new CSafeMemFile(256);
			m_hashset->WriteHash16(m_hash);
			m_hashset->WriteUInt16(0);

			int iPartHashs = 0;
			int iPosPH = 0;
			CString strHash = strPartHashs.Tokenize(_T(":"), iPosPH);
			while (!strHash.IsEmpty())
			{
				uchar aucPartHash[16];
				if (!strmd4(strHash, aucPartHash)){
					bError = true;
					break;
				}
				m_hashset->WriteHash16(aucPartHash);
				iPartHashs++;
				strHash = strPartHashs.Tokenize(_T(":"), iPosPH);
			}
			if (bError)
				break;

			m_hashset->Seek(16, CFile::begin);
			m_hashset->WriteUInt16(iPartHashs);
			m_hashset->Seek(0, CFile::begin);
		}
		else if (strTok == _T("h"))
		{
			CString strHash = strParam.Mid(iPos + 1);
			if (!strHash.IsEmpty())
			{
				if (DecodeBase32(strHash, m_AICHHash.GetRawHash(), CAICHHash::GetHashSize()) == CAICHHash::GetHashSize()){
					m_bAICHHashValid = true;
					ASSERT( m_AICHHash.GetString().CompareNoCase(strHash) == 0 );
				}
				else
					ASSERT( false );
			}
			else
				ASSERT( false );
		}
		else
			ASSERT(0);
	}

	if (bError)
	{
		delete m_hashset;
		m_hashset = NULL;
	}

	if (pszSources)
	{
		TCHAR* pNewString = _tcsdup(pszSources);
		autoFree liberator(pNewString);
		TCHAR* pCh = pNewString;
		TCHAR* pEnd;
		TCHAR* pIP;
		TCHAR* pPort;

		bool bAllowSources;
		TCHAR date[3];
		COleDateTime expirationDate;
		int nYear,nMonth,nDay;

		uint16 nCount = 0;
		uint32 dwID;
		uint16 nPort;
		uint32 dwServerIP = 0; 
		uint16 nServerPort = 0;
		unsigned long ul;

		int nInvalid = 0;

		pCh = _tcsstr( pCh, _T("sources") );
		if( pCh != NULL ) {
			pCh = pCh + 7; // point to char after "sources"
			pEnd = pCh;
			while( *pEnd ) pEnd++; // make pEnd point to the terminating NULL
			bAllowSources=true;
			// if there's an expiration date...
			if( *pCh == _T('@') && (pEnd-pCh) > 7 )
			{
				pCh++; // after '@'
				date[2] = 0; // terminate the two character string
				date[0] = *(pCh++); date[1] = *(pCh++);
				nYear = _tcstol( date, 0, 10 ) + 2000;
				date[0] = *(pCh++); date[1] = *(pCh++);
				nMonth = _tcstol( date, 0, 10 );
				date[0] = *(pCh++); date[1] = *(pCh++);
				nDay = _tcstol( date, 0, 10 );
				bAllowSources = ( expirationDate.SetDate(nYear,nMonth,nDay) == 0 );
				if (bAllowSources) bAllowSources=(COleDateTime::GetCurrentTime() < expirationDate);
			}

			// increment pCh to point to the first "ip:port" and check for sources
			if ( bAllowSources && ++pCh < pEnd ) {
				SourcesList = new CSafeMemFile(256);
				SourcesList->WriteUInt16(nCount); // init to 0, we'll fix this at the end.
				// for each "ip:port" source string until the end
				// limit to prevent overflow (uint16 due to CPartFile::AddClientSources)
				while( *pCh != 0 && nCount < MAXSHORT ) {
					pIP = pCh;
					// find the end of this ip:port string & start of next ip:port string.
					if( (pCh = _tcschr(pCh, _T(','))) != NULL ) {
						*pCh = 0; // terminate current "ip:port"
						pCh++; // point to next "ip:port"
					}
					else
						pCh = pEnd;

					// if port is not present for this ip, go to the next ip.
					if( (pPort = _tcschr(pIP, _T(':'))) == NULL )
					{	nInvalid++;	continue;	}

					*pPort = 0;	// terminate ip string
					pPort++;	// point pPort to port string.

					dwID = inet_addr(CStringA(pIP));
					ul = _tcstoul( pPort, 0, 10 );
					nPort = static_cast<uint16>(ul);

					// skip bad ips / ports
					if (ul > 0xFFFF || ul == 0 )	// port
					{	nInvalid++;	continue;	}
					if( dwID == INADDR_NONE) {	// hostname?
						if (_tcslen(pIP) > 512)
						{	nInvalid++;	continue;	}
						SUnresolvedHostname* hostname = new SUnresolvedHostname;
						hostname->nPort = nPort;
						hostname->strHostname = pIP;
						m_HostnameSourcesList.AddTail(hostname);
						continue;
					}
					//TODO: This will filter out *.*.*.0 clients. Is there a nice way to fix?
					if( IsLowID(dwID) )	// ip
					{	nInvalid++;	continue;	}

					SourcesList->WriteUInt32(dwID);
					SourcesList->WriteUInt16(nPort);
					SourcesList->WriteUInt32(dwServerIP);
					SourcesList->WriteUInt16(nServerPort);
					nCount++;
				}
				SourcesList->SeekToBegin();
				SourcesList->WriteUInt16(nCount);
				SourcesList->SeekToBegin();
				if (nCount==0) {
					delete SourcesList;
					SourcesList=NULL;
				}
			}
		}
	}
}
예제 #6
0
CGnuDownloadShell* CGnuTransfers::LoadDownloadHosts(CString FilePath)
{
	// Check if file already loaded
	for(int i = 0; i < m_DownloadList.size(); i++)
		if( m_DownloadList[i]->m_BackupPath.CompareNoCase(FilePath) == 0 )
			return NULL;


	CStdioFile BackupFile;

	CString NextLine;
	CString Backup;
	
	if (BackupFile.Open(FilePath, CFile::modeRead))
	{
		while (BackupFile.ReadString(NextLine))
			Backup += NextLine + "\n";

		BackupFile.Abort();
	}

	if(Backup.IsEmpty() || Backup.Find("[Download]") == -1)
		return NULL;

	int CurrentPos = Backup.Find("[Download]");

	CGnuDownloadShell* Download = new CGnuDownloadShell(this);
	
	Download->m_ShellStatus		= (CGnuDownloadShell::Status) atoi(GetBackupString("Status", CurrentPos, Backup));
	Download->m_Name			= GetBackupString("Name", CurrentPos, Backup);
	Download->m_FileLength		= _atoi64(GetBackupString("FileLength", CurrentPos, Backup));
	Download->m_PartSize		= atoi(GetBackupString("PartSize", CurrentPos, Backup));
	Download->m_OverrideName	= GetBackupString("OverrideName", CurrentPos, Backup);
	Download->m_OverridePath	= GetBackupString("OverridePath", CurrentPos, Backup);
	Download->m_PartialPath		= GetBackupString("PartialPath", CurrentPos, Backup);
	Download->m_BackupPath  	= FilePath;
	Download->m_Sha1Hash		= GetBackupString("Sha1Hash", CurrentPos, Backup);
	Download->m_Search			= GetBackupString("Search", CurrentPos, Backup);
	Download->m_AvgSpeed		= atoi(GetBackupString("AvgSpeed", CurrentPos, Backup));
	Download->m_HashComputed	= atoi(GetBackupString("HashComputed", CurrentPos, Backup));
	Download->m_HashVerified	= atoi(GetBackupString("HashVerified", CurrentPos, Backup));
	Download->m_FileMoved		= atoi(GetBackupString("FileMoved", CurrentPos, Backup));
	Download->m_ReasonDead		= GetBackupString("ReasonDead", CurrentPos, Backup);
	Download->m_MetaXml         = GetBackupString("Meta", CurrentPos, Backup);

	Download->m_UseProxy		= atoi(GetBackupString("UseProxy", CurrentPos, Backup));
	Download->m_DefaultProxy	= GetBackupString("DefaultProxy", CurrentPos, Backup);

	Download->m_TigerHash		= GetBackupString("TigerHash", CurrentPos, Backup);
	Download->m_TreeSize		= atoi(GetBackupString("TreeSize", CurrentPos, Backup));
	Download->m_TreeRes			= atoi(GetBackupString("TreeRes", CurrentPos, Backup));

	if(Download->m_TreeSize)
	{
		Download->m_TigerTree = new byte[Download->m_TreeSize];
		memset(Download->m_TigerTree, 0, Download->m_TreeSize);
	}

	if(Download->m_TigerTree)
	{
		CString Value = GetBackupString("TigerTree", CurrentPos, Backup);

		int buffPos = 0;
		int dotPos  = Value.Find(".");

		while(dotPos != -1 && buffPos < Download->m_TreeSize)
		{
			DecodeBase32( Value.Mid(dotPos - 39, 39), 39, Download->m_TigerTree + buffPos, Download->m_TreeSize - buffPos );

			buffPos += 24;
			dotPos = Value.Find(".", dotPos + 1);
		}
	}


	Download->Init(Download->m_Name, Download->m_FileLength, HASH_SHA1, Download->m_Sha1Hash);

	
	// Load Host info
	if( !Download->m_FileMoved )
		for(int i = 0; ; i++)
		{
			CurrentPos = Backup.Find("[Host " + NumtoStr(i) + "]");

			if(CurrentPos == -1)
				break;

			CurrentPos += 5; // Host in header and value conflict

			FileSource nResult;
			nResult.Name = GetBackupString("Name", CurrentPos, Backup);
			nResult.NameLower = nResult.Name;
			nResult.NameLower.MakeLower();

			nResult.Sha1Hash	 = GetBackupString("Sha1Hash", CurrentPos, Backup);
			//nResult.BitprintHash = GetBackupString("BitprintHash", CurrentPos, Backup);

			nResult.FileIndex	= atoi(GetBackupString("FileIndex", CurrentPos, Backup));
			nResult.Size		= _atoi64(GetBackupString("Size", CurrentPos, Backup));

			nResult.Address.Host = StrtoIP(GetBackupString("Host", CurrentPos, Backup));
			nResult.Address.Port = atoi(GetBackupString("Port", CurrentPos, Backup));
			nResult.Network      = atoi(GetBackupString("Network", CurrentPos, Backup));
			nResult.HostStr		 = GetBackupString("HostStr", CurrentPos, Backup);
			nResult.Path		 = GetBackupString("Path", CurrentPos, Backup);
			nResult.Speed		 = atoi(GetBackupString("Speed", CurrentPos, Backup));
			nResult.Vendor		 = GetBackupString("Vendor", CurrentPos, Backup);

			nResult.Firewall	= atoi(GetBackupString("Firewall", CurrentPos, Backup)) != 0;
			nResult.OpenSlots	= atoi(GetBackupString("OpenSlots", CurrentPos, Backup)) != 0;
			nResult.Busy		= atoi(GetBackupString("Busy", CurrentPos, Backup)) != 0;
			nResult.Stable		= atoi(GetBackupString("Stable", CurrentPos, Backup)) != 0;
			nResult.ActualSpeed = atoi(GetBackupString("ActualSpeed", CurrentPos, Backup)) != 0;
			nResult.SupportF2F  = atoi(GetBackupString("SupportF2F", CurrentPos, Backup)) != 0;
			DecodeBase16(GetBackupString("PushID", CurrentPos, Backup), 32, (byte*) &nResult.PushID, 16);

			CString Nodes = GetBackupString("Direct", CurrentPos, Backup);
			while(!Nodes.IsEmpty())
				nResult.DirectHubs.push_back( StrtoIPv4(ParseString(Nodes, ',')) );

			nResult.GnuRouteID = 0;
			nResult.Distance = 7;
			//nResult.Icon     = m_pCore->GetIconIndex(nResult.Name);

			Download->AddHost(nResult);
		}

	//Download->m_DoReQuery = true;


	// Add Download to list
	m_DownloadAccess.Lock();
	m_DownloadList.push_back(Download);
	m_DownloadAccess.Unlock();

	TransferLoadMeta();

	if(Download->m_ShellStatus == CGnuDownloadShell::eActive)
		Download->Start();

	return Download;
}