Esempio n. 1
0
void CCaHtmlParse::__GetSaleEndDate(CStringA & straEndDate, CStringA & straEndTime, const TidyDoc & tdoc, const TidyNode & tdNode)
{
	CStringA straRet;
	straEndDate = "";
	straEndTime = "";

	TidyBuffer text = {0};
	tidyBufInit(&text);
	TidyNodeType type = tidyNodeGetType(tdNode);
	tidyNodeGetText(tdoc, tdNode, &text);
	straRet.Format("%s",text.bp);
	straRet.TrimLeft();

	int iPos = straRet.Find("<br");
	straRet = straRet.Mid(4, iPos-4);
	straEndDate = straRet.Left(10);
	straEndTime = straRet.Mid(11);
	straEndTime.Trim();

	tidyBufFree(&text);
}
Esempio n. 2
0
void CSendFile::OnBnClickedButton1()
{
	// TODO: 在此添加控件通知处理程序代码
	UpdateData(TRUE);
	//发送请求
	//获取文件名
	CStringA filename = CW2A(m_strFilePath.GetBuffer(), CP_THREAD_ACP);
	int i = 0;
	while (i != -1)
	{
		i = filename.Find("\\");
		filename.Delete(0, i + 1);
	}

	m_strFileName = filename;

	filename += L":" + m_fid;
	
	m_client->Send(FILETRANS, filename.GetBuffer(), 1);

}
void DoFilePathName(CStringA resToken)
{
	CHAR expName[MAX_PATH + 1];
	ExpandEnvironmentStringsA(resToken, expName, MAX_PATH);
	resToken = expName;

	std::vector<CString>* pvecFiles = new std::vector<CString>;

	if (resToken.Find('*') != -1)
	{
		int nEnumSubdir = 0;
		int nLength = resToken.GetLength();
		if (nLength > 2 && resToken.Mid(nLength - 2).MakeLower() == "|s")
		{
			nEnumSubdir = 1;
			resToken = resToken.Mid(0, nLength - 2);
		}
		else if (nLength > 2 && resToken.Mid(nLength - 2).MakeLower() == "|a")
		{
			nEnumSubdir = 2;
			resToken = resToken.Mid(0, nLength - 2);
		}

		//std::vector<CString> vecFiles;
		EnumDir(resToken, nEnumSubdir, *pvecFiles);
	}
	else
	{
		USES_CONVERSION;

		pvecFiles->push_back(A2W(resToken));
	}

	g_sysModuleNameList.insert(g_sysModuleNameList.end(), (*pvecFiles).begin(), (*pvecFiles).end());
	delete pvecFiles;
}
Esempio n. 4
0
static int getColorTableIndex(CStringA& rtf)
{
	// the result
	int theIndex = 0;

	// see if the color table is present
	int clrTablePos = rtf.Find("{\\colortbl ;");

	// if not, insert one
	if (clrTablePos == -1)
	{
		// locate font table
		int fontTablePos = rtf.Find("\\fonttbl{");
		ASSERT(fontTablePos);
		if (fontTablePos == -1)
		{
			// This means that this is not something generated by
			// the guide. It is also unlikely that these will
			// have links that need to be fixed anyway.

			// For now just throw up our hands..
			ASSERT(FALSE);
			return -1;
		}

		// find the end of the font table
		int fontTableEndPos = rtf.Find("}}", fontTablePos);
		ASSERT(fontTableEndPos != -1);
		if (fontTableEndPos == -1)
			return -1; // duh.. unterminated font table?
		fontTableEndPos += 2;

		// insert the color table
		rtf.Insert(fontTableEndPos, "{\\colortbl ;\\red0\\green0\\blue255;}");

		// only one entry in the colour table, so the index is 1
		// (the index is 1-based).
		return 1;
	}

	// color table exists, add a new entry at the end.
	int clrTableEndPos = rtf.Find(";}", clrTablePos);
	ASSERT(clrTableEndPos != -1);
	if (clrTableEndPos == -1)
		return -1; // duh.. unterminated color table?
	clrTableEndPos += 2;

	// before inserting, count the number of existing entries.
	const char *p = (const char *)rtf + clrTablePos + sizeof("{\\colortbl ;"); // just beyond the ;
	const char *q = (const char *)rtf + clrTableEndPos;
	int count = 0;
	while (p < q)
	{
		if (*p == ';')
			++count;
		++p;
	}

	// insert the new entry.
	rtf.Insert(clrTableEndPos-1, "\\red0\\green0\\blue255;");

	// return the index
	return count + 1;
}
Esempio n. 5
0
BOOL CHttpDataParser::ParseRecvData( PBYTE pRecvData,int nRecvDataLen,BOOL *pbFinalData)
{
	BOOL bAddRes = FALSE;
	do 
	{
		if ( NULL == pRecvData || nRecvDataLen == 0 )
		{
			break;
		}

		//如果还没有接受到头部,则缓存数据,等待头部
		if ( FALSE == m_bHeaderOk )
		{
			m_bufHead.AppendData(pRecvData,nRecvDataLen);
		}
		else
		{
			m_bufContent.AppendData(pRecvData,nRecvDataLen);
		}

		if ( FALSE == m_bHeaderOk )
		{
			BYTE *pHeadDataBuffer = m_bufHead.GetDataBuffer();
			LONGLONG llHeadDataLen = m_bufHead.GetTotalBufferLen();
			CHttpRecvParser recvparser;
			if (recvparser.ParseData((const char *)pHeadDataBuffer,llHeadDataLen) )
			{
				m_bHeaderOk = TRUE;

				m_nContentStart = recvparser.GetContentStart();

				int nRecvContentLen = llHeadDataLen - m_nContentStart;
				if ( nRecvContentLen > 0 )
				{
					m_bufContent.AppendData(pHeadDataBuffer+m_nContentStart,nRecvContentLen);
				}

				m_pCallback(m_pCallbackParam,pHeadDataBuffer,m_nContentStart,TRUE);

				CStringA strContentLen;
				CStringA strContentEncoding;
				CStringA strTransferEncoding;

				strContentLen = recvparser.GetValueByName("Content-Length");
				strContentEncoding = recvparser.GetValueByName("Content-Encoding");
				strTransferEncoding = recvparser.GetValueByName("Transfer-Encoding");

				if ( !strContentLen.IsEmpty() )
				{
					//没有传输编码
					m_teEncoding = TE_NO_ENCODING;
					m_llTotalContentLen = _ttoi64(CString(strContentLen));
				}
				else if( !strTransferEncoding.IsEmpty() )
				{
					//有传输编码
					if ( strTransferEncoding.CompareNoCase("chunked") == 0 )
					{
						m_teEncoding = TE_CHUNKED;
					}
					else
					{
						ASSERT(FALSE);
					}
				}
				else
				{
					m_teEncoding = TE_NO_ENCODING;
					m_llTotalContentLen = 0;
				}

				if( !strContentEncoding.IsEmpty() )
				{
					//内容有压缩编码
					if ( strContentEncoding.Find("gzip") >= 0 )
					{
						m_ceEncoding = CE_GZIP;
					}
					else
					{
						m_ceEncoding = CE_UNKNOWN;
					}
				}
				else
				{
					m_ceEncoding = CE_NO_ENCODING;
				}
			}
		}

		if ( m_bHeaderOk )
		{
			BYTE *pContentDataBuffer = m_bufContent.GetDataBuffer();
			LONGLONG llContentDataLen = m_bufContent.GetTotalBufferLen();

			if ( pContentDataBuffer && llContentDataLen )
			{
				HandleContentData( pContentDataBuffer , llContentDataLen,pbFinalData);
				m_bufContent.DestoryData();
			}
		}

		bAddRes = TRUE;

	} while (FALSE);

	return bAddRes;
}
Esempio n. 6
0
bool CWebServer::CallCGI(CWebClientSocket* pClient, CStringA& hdr, CStringA& body, CStringA& mime)
{
    CString path = pClient->m_path, redir = path;
    if (!ToLocalPath(path, redir)) {
        return false;
    }
    CString ext = CPath(path).GetExtension().MakeLower();
    CPath dir(path);
    dir.RemoveFileSpec();

    CString cgi;
    if (!m_cgi.Lookup(ext, cgi) || !CPath(cgi).FileExists()) {
        return false;
    }

    HANDLE hProcess = GetCurrentProcess();
    HANDLE hChildStdinRd, hChildStdinWr, hChildStdinWrDup = NULL;
    HANDLE hChildStdoutRd, hChildStdoutWr, hChildStdoutRdDup = NULL;

    SECURITY_ATTRIBUTES saAttr;
    ZeroMemory(&saAttr, sizeof(saAttr));
    saAttr.nLength = sizeof(saAttr);
    saAttr.bInheritHandle = TRUE;

    if (CreatePipe(&hChildStdoutRd, &hChildStdoutWr, &saAttr, 0)) {
        BOOL fSuccess = DuplicateHandle(hProcess, hChildStdoutRd, hProcess, &hChildStdoutRdDup, 0, FALSE, DUPLICATE_SAME_ACCESS);
        UNREFERENCED_PARAMETER(fSuccess);
        CloseHandle(hChildStdoutRd);
    }

    if (CreatePipe(&hChildStdinRd, &hChildStdinWr, &saAttr, 0)) {
        BOOL fSuccess = DuplicateHandle(hProcess, hChildStdinWr, hProcess, &hChildStdinWrDup, 0, FALSE, DUPLICATE_SAME_ACCESS);
        UNREFERENCED_PARAMETER(fSuccess);
        CloseHandle(hChildStdinWr);
    }

    STARTUPINFO siStartInfo;
    ZeroMemory(&siStartInfo, sizeof(siStartInfo));
    siStartInfo.cb = sizeof(siStartInfo);
    siStartInfo.hStdError = hChildStdoutWr;
    siStartInfo.hStdOutput = hChildStdoutWr;
    siStartInfo.hStdInput = hChildStdinRd;
    siStartInfo.dwFlags |= STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
    siStartInfo.wShowWindow = SW_HIDE;

    PROCESS_INFORMATION piProcInfo;
    ZeroMemory(&piProcInfo, sizeof(piProcInfo));

    CStringA envstr;

    LPVOID lpvEnv = GetEnvironmentStrings();
    if (lpvEnv) {
        CString str;

        CAtlList<CString> env;
        for (LPTSTR lpszVariable = (LPTSTR)lpvEnv; *lpszVariable; lpszVariable += _tcslen(lpszVariable) + 1)
            if (lpszVariable != (LPTSTR)lpvEnv) {
                env.AddTail(lpszVariable);
            }

        env.AddTail(_T("GATEWAY_INTERFACE=CGI/1.1"));
        env.AddTail(_T("SERVER_SOFTWARE=Media Player Classic - Home Cinema/") MPC_VERSION_STR);
        env.AddTail(_T("SERVER_PROTOCOL=") + pClient->m_ver);
        env.AddTail(_T("REQUEST_METHOD=") + pClient->m_cmd);
        env.AddTail(_T("PATH_INFO=") + redir);
        env.AddTail(_T("PATH_TRANSLATED=") + path);
        env.AddTail(_T("SCRIPT_NAME=") + redir);
        env.AddTail(_T("QUERY_STRING=") + pClient->m_query);

        if (pClient->m_hdrlines.Lookup(_T("content-type"), str)) {
            env.AddTail(_T("CONTENT_TYPE=") + str);
        }
        if (pClient->m_hdrlines.Lookup(_T("content-length"), str)) {
            env.AddTail(_T("CONTENT_LENGTH=") + str);
        }

        POSITION pos = pClient->m_hdrlines.GetStartPosition();
        while (pos) {
            CString key = pClient->m_hdrlines.GetKeyAt(pos);
            CString value = pClient->m_hdrlines.GetNextValue(pos);
            key.Replace(_T("-"), _T("_"));
            key.MakeUpper();
            env.AddTail(_T("HTTP_") + key + _T("=") + value);
        }

        CString name;
        UINT port;

        if (pClient->GetPeerName(name, port)) {
            str.Format(_T("%d"), port);
            env.AddTail(_T("REMOTE_ADDR=") + name);
            env.AddTail(_T("REMOTE_HOST=") + name);
            env.AddTail(_T("REMOTE_PORT=") + str);
        }

        if (pClient->GetSockName(name, port)) {
            str.Format(_T("%d"), port);
            env.AddTail(_T("SERVER_NAME=") + name);
            env.AddTail(_T("SERVER_PORT=") + str);
        }

        env.AddTail(_T("\0"));

        str = Implode(env, '\0');
        envstr = CStringA(str, str.GetLength());

        FreeEnvironmentStrings((LPTSTR)lpvEnv);
    }

    TCHAR* cmdln = DNew TCHAR[32768];
    _sntprintf_s(cmdln, 32768, 32768, _T("\"%s\" \"%s\""), cgi, path);

    if (hChildStdinRd && hChildStdoutWr)
        if (CreateProcess(
                    NULL, cmdln, NULL, NULL, TRUE, 0,
                    envstr.GetLength() ? (LPVOID)(LPCSTR)envstr : NULL,
                    dir, &siStartInfo, &piProcInfo)) {
            DWORD ThreadId;
            CreateThread(NULL, 0, KillCGI, (LPVOID)piProcInfo.hProcess, 0, &ThreadId);

            static const int BUFFSIZE = 1024;
            DWORD dwRead, dwWritten = 0;

            int i = 0, len = pClient->m_data.GetLength();
            for (; i < len; i += dwWritten)
                if (!WriteFile(hChildStdinWrDup, (LPCSTR)pClient->m_data + i, min(len - i, BUFFSIZE), &dwWritten, NULL)) {
                    break;
                }

            CloseHandle(hChildStdinWrDup);
            CloseHandle(hChildStdoutWr);

            body.Empty();

            CStringA buff;
            while (i == len && ReadFile(hChildStdoutRdDup, buff.GetBuffer(BUFFSIZE), BUFFSIZE, &dwRead, NULL) && dwRead) {
                buff.ReleaseBufferSetLength(dwRead);
                body += buff;
            }

            int hdrend = body.Find("\r\n\r\n");
            if (hdrend >= 0) {
                hdr = body.Left(hdrend + 2);
                body = body.Mid(hdrend + 4);
            }

            CloseHandle(hChildStdinRd);
            CloseHandle(hChildStdoutRdDup);

            CloseHandle(piProcInfo.hProcess);
            CloseHandle(piProcInfo.hThread);
        } else {
            body = _T("CGI Error");
        }

    delete [] cmdln;

    return true;
}
Esempio n. 7
0
int CIPFilter::AddFromFile(LPCTSTR pszFilePath, bool bShowResponse)
{
	DWORD dwStart = GetTickCount();
	FILE* readFile = _tfsopen(pszFilePath, _T("r"), _SH_DENYWR);
	if (readFile != NULL)
	{
		enum EIPFilterFileType
		{
			Unknown = 0,
			FilterDat = 1,		// ipfilter.dat/ip.prefix format
			PeerGuardian = 2,	// PeerGuardian text format
			PeerGuardian2 = 3	// PeerGuardian binary format
		} eFileType = Unknown;

		setvbuf(readFile, NULL, _IOFBF, 32768);

		TCHAR szNam[_MAX_FNAME];
		TCHAR szExt[_MAX_EXT];
		_tsplitpath(pszFilePath, NULL, NULL, szNam, szExt);
		if (_tcsicmp(szExt, _T(".p2p")) == 0 || (_tcsicmp(szNam, _T("guarding.p2p")) == 0 && _tcsicmp(szExt, _T(".txt")) == 0))
			eFileType = PeerGuardian;
		else if (_tcsicmp(szExt, _T(".prefix")) == 0)
			eFileType = FilterDat;
		else
		{
			VERIFY( _setmode(fileno(readFile), _O_BINARY) != -1 );
			static const BYTE _aucP2Bheader[] = "\xFF\xFF\xFF\xFFP2B";
			BYTE aucHeader[sizeof _aucP2Bheader - 1];
			if (fread(aucHeader, sizeof aucHeader, 1, readFile) == 1)
			{
				if (memcmp(aucHeader, _aucP2Bheader, sizeof _aucP2Bheader - 1)==0)
					eFileType = PeerGuardian2;
				else
				{
					(void)fseek(readFile, 0, SEEK_SET);
					VERIFY( _setmode(fileno(readFile), _O_TEXT) != -1 ); // ugly!
				}
			}
		}

		int iFoundRanges = 0;
		int iLine = 0;
		if (eFileType == PeerGuardian2)
		{
			// Version 1: strings are ISO-8859-1 encoded
			// Version 2: strings are UTF-8 encoded
			uint8 nVersion;
			if (fread(&nVersion, sizeof nVersion, 1, readFile)==1 && (nVersion==1 || nVersion==2))
			{
				while (!feof(readFile))
				{
					CHAR szName[256];
					int iLen = 0;
					for (;;) // read until NUL or EOF
					{
						int iChar = getc(readFile);
						if (iChar == EOF)
							break;
						if (iLen < sizeof szName - 1)
							szName[iLen++] = (CHAR)iChar;
						if (iChar == '\0')
							break;
					}
					szName[iLen] = '\0';
					
					uint32 uStart;
					if (fread(&uStart, sizeof uStart, 1, readFile) != 1)
						break;
					uStart = ntohl(uStart);

					uint32 uEnd;
					if (fread(&uEnd, sizeof uEnd, 1, readFile) != 1)
						break;
					uEnd = ntohl(uEnd);

					iLine++;
					// (nVersion == 2) ? OptUtf8ToStr(szName, iLen) : 
					AddIPRange(uStart, uEnd, DFLT_FILTER_LEVEL, CStringA(szName, iLen));
					iFoundRanges++;
				}
			}
		}
		else
		{
			CStringA sbuffer;
			CHAR szBuffer[1024];
			while (fgets(szBuffer, _countof(szBuffer), readFile) != NULL)
			{
				iLine++;
				sbuffer = szBuffer;
				
				// ignore comments & too short lines
				if (sbuffer.GetAt(0) == '#' || sbuffer.GetAt(0) == '/' || sbuffer.GetLength() < 5) {
					sbuffer.Trim(" \t\r\n");
					DEBUG_ONLY( (!sbuffer.IsEmpty()) ? TRACE("IP filter: ignored line %u\n", iLine) : 0 );
					continue;
				}

				if (eFileType == Unknown)
				{
					// looks like html
					if (sbuffer.Find('>') > -1 && sbuffer.Find('<') > -1)
						sbuffer.Delete(0, sbuffer.ReverseFind('>') + 1);

					// check for <IP> - <IP> at start of line
					UINT u1, u2, u3, u4, u5, u6, u7, u8;
					if (sscanf(sbuffer, "%u.%u.%u.%u - %u.%u.%u.%u", &u1, &u2, &u3, &u4, &u5, &u6, &u7, &u8) == 8)
					{
						eFileType = FilterDat;
					}
					else
					{
						// check for <description> ':' <IP> '-' <IP>
						int iColon = sbuffer.Find(':');
						if (iColon > -1)
						{
							CStringA strIPRange = sbuffer.Mid(iColon + 1);
							UINT u1, u2, u3, u4, u5, u6, u7, u8;
							if (sscanf(strIPRange, "%u.%u.%u.%u - %u.%u.%u.%u", &u1, &u2, &u3, &u4, &u5, &u6, &u7, &u8) == 8)
							{
								eFileType = PeerGuardian;
							}
						}
					}
				}

				bool bValid = false;
				uint32 start = 0;
				uint32 end = 0;
				UINT level = 0;
				CStringA desc;
				if (eFileType == FilterDat)
					bValid = ParseFilterLine1(sbuffer, start, end, level, desc);
				else if (eFileType == PeerGuardian)
					bValid = ParseFilterLine2(sbuffer, start, end, level, desc);

				// add a filter
				if (bValid)
				{
					AddIPRange(start, end, level, desc);
					iFoundRanges++;
				}
				else
				{
					sbuffer.Trim(" \t\r\n");
					DEBUG_ONLY( (!sbuffer.IsEmpty()) ? TRACE("IP filter: ignored line %u\n", iLine) : 0 );
				}
			}
		}
		fclose(readFile);

		// sort the IP filter list by IP range start addresses
		qsort(m_iplist.GetData(), m_iplist.GetCount(), sizeof(m_iplist[0]), CmpSIPFilterByStartAddr);

		// merge overlapping and adjacent filter ranges
		int iDuplicate = 0;
		int iMerged = 0;
		if (m_iplist.GetCount() >= 2)
		{
			// On large IP-filter lists there is a noticeable performance problem when merging the list.
			// The 'CIPFilterArray::RemoveAt' call is way too expensive to get called during the merging,
			// thus we use temporary helper arrays to copy only the entries into the final list which
			// are not get deleted.

			// Reserve a byte array (its used as a boolean array actually) as large as the current 
			// IP-filter list, so we can set a 'to delete' flag for each entry in the current IP-filter list.
			char* pcToDelete = new char[m_iplist.GetCount()];
			memset(pcToDelete, 0, m_iplist.GetCount());
			int iNumToDelete = 0;

			SIPFilter* pPrv = m_iplist[0];
			int i = 1;
			while (i < m_iplist.GetCount())
			{
				SIPFilter* pCur = m_iplist[i];
				if (   pCur->start >= pPrv->start && pCur->start <= pPrv->end	 // overlapping
					|| pCur->start == pPrv->end+1 && pCur->level == pPrv->level) // adjacent
				{
					if (pCur->start != pPrv->start || pCur->end != pPrv->end) // don't merge identical entries
					{
						//TODO: not yet handled, overlapping entries with different 'level'
						if (pCur->end > pPrv->end)
							pPrv->end = pCur->end;
						//pPrv->desc += _T("; ") + pCur->desc; // this may create a very very long description string...
						iMerged++;
					}
					else
					{
						// if we have identical entries, use the lowest 'level'
						if (pCur->level < pPrv->level)
							pPrv->level = pCur->level;
						iDuplicate++;
					}
					delete pCur;
					//m_iplist.RemoveAt(i);	// way too expensive (read above)
					pcToDelete[i] = 1;		// mark this entry as 'to delete'
					iNumToDelete++;
					i++;
					continue;
				}
				pPrv = pCur;
				i++;
			}

			// Create new IP-filter list which contains only the entries from the original IP-filter list
			// which are not to be deleted.
			if (iNumToDelete > 0)
			{
				CIPFilterArray newList;
				newList.SetSize(m_iplist.GetCount() - iNumToDelete);
				int iNewListIndex = 0;
				for (int i = 0; i < m_iplist.GetCount(); i++) {
					if (!pcToDelete[i])
						newList[iNewListIndex++] = m_iplist[i];
				}
				ASSERT( iNewListIndex == newList.GetSize() );

				// Replace current list with new list. Dump, but still fast enough (only 1 memcpy)
				m_iplist.RemoveAll();
				m_iplist.Append(newList);
				newList.RemoveAll();
				m_bModified = true;
			}
			delete[] pcToDelete;
		}

		if (thePrefs.GetVerbose())
		{
			DWORD dwEnd = GetTickCount();
			AddDebugLogLine(false, _T("Loaded IP filters from \"%s\""), pszFilePath);
			AddDebugLogLine(false, _T("Parsed lines/entries:%u  Found IP ranges:%u  Duplicate:%u  Merged:%u  Time:%s"), iLine, iFoundRanges, iDuplicate, iMerged, CastSecondsToHM((dwEnd-dwStart+500)/1000));
		}
		AddLogLine(bShowResponse, GetResString(IDS_IPFILTERLOADED), m_iplist.GetCount());
	}
	return m_iplist.GetCount();
}
Esempio n. 8
0
BOOL CCookie::ParseExpires(LPCSTR lpszExpires, __time64_t& tmExpires)
{
	int iLength = (int)strlen(lpszExpires);

	if(iLength == 0 || iLength > 50)
		return FALSE;

	char szMonth[10];
	char szZone[10];

	tm t = {0};

	if(sscanf(	lpszExpires, "%*[^, ]%*[, ]%2d%*[-/ ]%8[^-/ ]%*[-/ ]%4d %2d:%2d:%2d %8c", 
				&t.tm_mday, szMonth, &t.tm_year, &t.tm_hour, &t.tm_min, &t.tm_sec, szZone) != 7)
		return FALSE;

	if(t.tm_year < 70)
		t.tm_year += 100;
	else if (t.tm_year > 100)
		t.tm_year -= 1900;

	int i	 = 0;
	int size = _countof(s_short_month);

	for(; i < size; i++)
	{
		if(strnicmp(szMonth, s_short_month[i], 3) == 0)
			break;
	}

	if(i == size)
		return FALSE;

	t.tm_mon = i;

	CStringA strZone = szZone;

	int iZone	= 0;
	int iMix	= 0;
	int iPos	= strZone.Find('+');

	if(iPos >= 0)
		iMix = 1;
	else
	{
		iPos = strZone.Find('-');

		if(iPos >= 0)
			iMix = -1;
	}

	if(iPos >= 0)
	{
		strZone = strZone.Mid(iPos + 1);
		strZone.Remove(':');

		int val = atoi(strZone);

		if(val > 0)
		{
			int minutes	= val % 100;
			int hours	= val / 100;

			iZone = iMix * (minutes * 60 + hours * 3600);
		}
	}

	tmExpires = GetUTCTime(t, iZone);

	return tmExpires >= 0;
}
Esempio n. 9
0
BOOL LoadResources(LPCTSTR szFilename)
{
	FILE* pFile = NULL;
	if ( _tfopen_s( &pFile, szFilename, _T("rb") ) == 0 )
	{
		CStringA sID;
		for ( States nState = stFile ; nState != stError ; )
		{
			CStringA sLine;
			CHAR* res = fgets( sLine.GetBuffer( 4096 ), 4096, pFile );
			sLine.ReleaseBuffer();
			if ( ! res )
			{
				if ( nState != stFile )
					_tprintf( _T("Error: Unexpected end of file\n") );

				break;		// End of file
			}
			sLine.Trim( ", \t\r\n" );
			if ( sLine.IsEmpty() ||
				 sLine.GetAt( 0 ) == '/' ||
				 sLine.GetAt( 0 ) == '#' )
				continue;	// Skip empty line, comment and pragma

			switch ( nState )
			{
			case stFile:
				if ( sLine == "STRINGTABLE" )
					nState = stStringTable;
				else if ( sLine == "GUIDELINES DESIGNINFO" )
					nState = stGuidelines;
				else
				{
					int nPos = sLine.Find( " DIALOG" );		// DIALOG or DIALOGEX
					if ( nPos != -1 )
					{
						CStringA sID = sLine.SpanExcluding( " " );
						UINT nID;
						if ( ! g_oIDs.Lookup( sID, nID ) )
						{
							_tprintf( _T("Error: Unknown ID \"%hs\" inside DIALOG\n"), sID );
							return 2;
						}
						if ( g_oDialogs.Lookup( sID, nID ) )
						{
							_tprintf( _T("Error: Duplicate ID \"%hs\" inside DIALOG\n"), sID );
							return 2;
						}
						g_oDialogs.SetAt( sID, nID );
					}

					nPos = sLine.Find( " ICON " );
					if ( nPos != -1 )
					{
						CStringA sID = sLine.SpanExcluding( " " );
						UINT nID;
						if ( ! g_oIDs.Lookup( sID, nID ) )
						{
							_tprintf( _T("Error: Unknown ID \"%hs\" of ICON\n"), sID );
							return 2;
						}
						if ( g_oIcons.Lookup( sID, nID ) )
						{
							_tprintf( _T("Error: Duplicate ID \"%hs\" of ICON\n"), sID );
							return 2;
						}
						g_oIcons.SetAt( sID, nID );
					}

					nPos = sLine.Find( " HTML " );
					if ( nPos == -1 )
						nPos = sLine.Find( " GZIP " );
					if ( nPos != -1 )
					{
						CStringA sID = sLine.SpanExcluding( " " );
						UINT nID;
						if ( ! g_oIDs.Lookup( sID, nID ) )
						{
							_tprintf( _T("Error: Unknown ID \"%hs\" of HTML\n"), sID );
							return 2;
						}
						if ( g_oHtmls.Lookup( sID, nID ) )
						{
							_tprintf( _T("Error: Duplicate ID \"%hs\" of HTML\n"), sID );
							return 2;
						}
						g_oHtmls.SetAt( sID, nID );
					}

					nPos = sLine.Find( " BITMAP " );
					if ( nPos == -1 )
						nPos = sLine.Find( " JPEG " );
					if ( nPos == -1 )
						nPos = sLine.Find( " PNG " );
					if ( nPos != -1 )
					{
						CStringA sID = sLine.SpanExcluding( " " );
						UINT nID;
						if ( ! g_oIDs.Lookup( sID, nID ) )
						{
							_tprintf( _T("Error: Unknown ID \"%hs\" of BITMAP\n"), sID );
							return 2;
						}
						if ( g_oBitmaps.Lookup( sID, nID ) )
						{
							_tprintf( _T("Error: Duplicate ID \"%hs\" of BITMAP\n"), sID );
							return 2;
						}
						g_oBitmaps.SetAt( sID, nID );
					}
				}
				break;

			case stGuidelines:
				if ( sLine == "BEGIN" )
					nState = stGuidelinesContent;
				else
				{
					_tprintf( _T("Error: BEGIN not found after GUIDELINES DESIGNINFO\n") );
					return 2;
				}
				break;

			case stGuidelinesContent:
				if ( sLine == "END" )
					nState = stFile;
				else if ( sLine.Right( 6 ) == "DIALOG" )
				{
					nState = stGuidelinesDialog;
					CStringA sID = sLine.SpanExcluding( "," );
					UINT nID;
					if ( ! g_oIDs.Lookup( sID, nID ) )
					{
						_tprintf( _T("Error: Unknown dialog ID \"%hs\" inside GUIDELINES\n"), sID );
						return 2;
					}
					if ( g_oGuidelines.Lookup( sID, nID ) )
					{
						_tprintf( _T("Error: Duplicate dialog ID \"%hs\" inside GUIDELINES\n"), sID );
						return 2;
					}
					if ( ! g_oDialogs.Lookup( sID, nID ) )
					{
						_tprintf( _T("Error: Orphan dialog ID \"%hs\" inside GUIDELINES\n"), sID );
						return 2;
					}
					g_oGuidelines.SetAt( sID, nID );
				}
				else
				{
					_tprintf( _T("Error: Unknown line \"%hs\" inside GUIDELINES\n"), sLine );
					return 2;
				}
				break;

			case stGuidelinesDialog:
				if ( sLine == "END" )
					nState = stGuidelinesContent;
				break;

			case stStringTable:
				if ( sLine == "BEGIN" )
					nState = stContent;
				else
				{
					_tprintf( _T("Error: BEGIN not found after STRINGTABLE\n") );
					return 2;
				}
				break;

			case stContent:
				if ( sLine == "END" )
					nState = stFile;
				else
				{
					int nPos = sLine.FindOneOf( ", \t" );
					if ( nPos != -1 )
					{
						if ( ProcessString( sLine.Left( nPos ),
							sLine.Mid( nPos + 1 ).TrimLeft( ", \t" ) ) )
							nState = stContent;
						else
							nState = stError;
					}
					else
					{
						sID = sLine;
						nState =  stString;
					}
				}
				break;

			case stString:
				if ( ProcessString( sID, sLine ) )
					nState = stContent;
				else
					nState = stError;
				sID.Empty();
				break;
			}
		}

		fclose( pFile );
	}

	return TRUE;
}
Esempio n. 10
0
// 根据字符串获取键盘码
void CDuiObject::ParseKeyCode(LPCTSTR lpszValue, UINT& nChar, UINT& nFlag)
{
	CStringA strValue;
	strValue = lpszValue;
	nChar = 0;
	nFlag = 0;
	strValue.Trim();
	strValue.MakeUpper();
	CStringA strFlag = "";
	CStringA strChar = strValue;
	int nPos = strValue.Find("+");
	if(nPos != -1)
	{
		strFlag = strValue.Left(nPos);
		strValue.Delete(0, nPos+1);
		strChar = strValue;
		strFlag.Trim();
		strChar.Trim();
	}

	if(strChar.IsEmpty())
	{
		return;
	}

	if(strFlag == "CTRL")
	{
		nFlag |= VK_CONTROL;
	}else
	if(strFlag == "ALT")
	{
		nFlag |= VK_MENU;
	}else
	if(strFlag == "SHIFT")
	{
		nFlag |= VK_SHIFT;
	}

	if(strChar == "RETURN")
	{
		nChar = VK_RETURN;
	}else
	if(strChar == "ESC")
	{
		nChar = VK_ESCAPE;
	}else
	if(strChar == "BACK")
	{
		nChar = VK_BACK;
	}else
	if(strChar == "TAB")
	{
		nChar = VK_TAB;
	}else
	if(strChar == "SPACE")
	{
		nChar = VK_SPACE;
	}else
	if(strChar == "PRIOR")
	{
		nChar = VK_PRIOR;
	}else
	if(strChar == "NEXT")
	{
		nChar = VK_NEXT;
	}else
	if(strChar == "END")
	{
		nChar = VK_END;
	}else
	if(strChar == "HOME")
	{
		nChar = VK_HOME;
	}else
	if(strChar == "LEFT")
	{
		nChar = VK_LEFT;
	}else
	if(strChar == "UP")
	{
		nChar = VK_UP;
	}else
	if(strChar == "RIGHT")
	{
		nChar = VK_RIGHT;
	}else
	if(strChar == "DOWN")
	{
		nChar = VK_DOWN;
	}else
	if(strChar == "SELECT")
	{
		nChar = VK_SELECT;
	}else
	if(strChar == "PRINT")
	{
		nChar = VK_PRINT;
	}else
	if(strChar == "INSERT")
	{
		nChar = VK_INSERT;
	}else
	if(strChar == "DELETE")
	{
		nChar = VK_DELETE;
	}else
	if(strChar == "F1")
	{
		nChar = VK_F1;
	}else
	if(strChar == "F2")
	{
		nChar = VK_F2;
	}else
	if(strChar == "F3")
	{
		nChar = VK_F3;
	}else
	if(strChar == "F4")
	{
		nChar = VK_F4;
	}else
	if(strChar == "F5")
	{
		nChar = VK_F5;
	}else
	if(strChar == "F6")
	{
		nChar = VK_F6;
	}else
	if(strChar == "F7")
	{
		nChar = VK_F7;
	}else
	if(strChar == "F8")
	{
		nChar = VK_F8;
	}else
	if(strChar == "F9")
	{
		nChar = VK_F9;
	}else
	if(strChar == "F10")
	{
		nChar = VK_F10;
	}else
	if(strChar == "F11")
	{
		nChar = VK_F11;
	}else
	if(strChar == "F12")
	{
		nChar = VK_F12;
	}else
	{
		char ch = strChar[0];
		if(((ch >= '0') && (ch < '9')) || ((ch >= 'A') && (ch < 'Z')))
		{
			nChar = ch;
		}
	}
}
Esempio n. 11
0
BOOL CHttpRecvParser::ParseData(const char * pBuffer,int nLen)
{
	BOOL bRes = FALSE;
	if (pBuffer == NULL || nLen < 50 )
	{
		return bRes;
	}



	CStringA strData;
	strData = pBuffer;

	CStringA strHttpHeader;
	int HttpHeadEnd = strData.Find("\r\n\r\n");
	if ( HttpHeadEnd > 0 )
	{
		char chHeadData[9];
		memcpy_s(chHeadData,8,pBuffer,8);
		chHeadData[8] = 0;

		
		if( StrCmpIA(chHeadData,"http/1.1") == 0 || StrCmpIA(chHeadData,"http/1.0") == 0 )
		{
			m_bResponseHead = TRUE;
			m_ContentStart = HttpHeadEnd+4;
			bRes = TRUE;
		}
		else
		{
			return FALSE;
		}

		strHttpHeader = strData.Left(HttpHeadEnd);

		CStringA strHeaders[MAX_ACCEPT_HEAD_LEN];
		int nCount = DivisionString("\r\n",strHttpHeader,strHeaders,MAX_ACCEPT_HEAD_LEN);
		if (nCount >= 1)
		{
			CStringA strTempStrs[10];
			int nTempCount = DivisionString(" ",strHeaders[0],strTempStrs,10);
			m_strHttpVersion = strTempStrs[0];
			m_strResponseCode = strTempStrs[1];

			for (int i=2;i<nTempCount;i++)
			{
				m_strResponseText += strTempStrs[i]+" ";
			}
			m_strResponseText.TrimRight();
			

			for(int i = 1;i<nCount;i++)
			{
				CStringA strHeader;
				CStringA strValue;
				int nHeadEnd = strHeaders[i].Find(":");
				if ( nHeadEnd > 0 )
				{
					strHeader = strHeaders[i].Left(nHeadEnd);
					strValue = strHeaders[i].Right(strHeaders[i].GetLength() - nHeadEnd - 1);
					strValue.Trim();
					AddResponseNode(strHeader,strValue);
				}

				
			}
			
		}
	}
	else
	{
		
	}

	return bRes;
}
Esempio n. 12
0
CStringA CPathUtils::PathEscape(const CStringA& path)
{
    CStringA ret2;
    int c;
    int i;
    for (i=0; path[i]; ++i)
    {
        c = (unsigned char)path[i];
        if (iri_escape_chars[c])
        {
            // no escaping needed for that char
            ret2 += (unsigned char)path[i];
        }
        else
        {
            // char needs escaping
            CStringA temp;
            temp.Format("%%%02X", (unsigned char)c);
            ret2 += temp;
        }
    }
    CStringA ret;
    for (i=0; ret2[i]; ++i)
    {
        c = (unsigned char)ret2[i];
        if (uri_autoescape_chars[c])
        {
            if ((c == '%')&&(DoesPercentNeedEscaping(ret2.Mid(i))))
            {
                // this percent sign needs escaping!
                CStringA temp;
                temp.Format("%%%02X", (unsigned char)c);
                ret += temp;
            }
            else
            {
                // no escaping needed for that char
                ret += (unsigned char)ret2[i];
            }
        }
        else
        {
            // char needs escaping
            CStringA temp;
            temp.Format("%%%02X", (unsigned char)c);
            ret += temp;
        }
    }

    if ((ret.Left(11).Compare("file:///%5C") == 0) && (ret.Find('%', 12) < 0))
        ret.Replace(("file:///%5C"), ("file://"));
    ret.Replace(("file:////%5C"), ("file://"));

    // properly handle ipv6 addresses
    int urlpos = ret.Find("://%5B");
    if (urlpos > 0)
    {
        int domainpos = ret.Find("/", urlpos+6);
        if (domainpos > urlpos)
        {
            CStringA leftpart = ret.Left(domainpos+1);
            if ((leftpart.Find("%5D:")>0)||(leftpart.Find("%5D/")>0))
            {
                leftpart.Replace("://%5B", "://[");
                leftpart.Replace("%5D/", "]/");
                leftpart.Replace("%5D:", "]:");
                ret = leftpart + ret.Mid(domainpos+1);
            }
        }
    }
    return ret;
}
Esempio n. 13
0
// 重载加载XML节点函数,加载下层的Menu item信息
BOOL CDuiMenu::Load(TiXmlElement* pXmlElem, BOOL bLoadSubControl)
{
	SetRect(CRect(0, 0, m_nWidth, m_nHeight));

	__super::Load(pXmlElem, bLoadSubControl);

	if(pXmlElem == NULL)
	{
		return FALSE;
	}

	if(!bLoadSubControl)
	{
		// 不加载子控件
		return TRUE;
	}

	// 菜单窗口宽度设置为popup窗口的宽度
	m_nWidth = m_size.cx;

	// 创建窗口
	Create(m_pParent, m_point, m_uMessageID);
	
	// 加载下层的item节点信息(正常情况下都使用DlgPopup的Load控件方式加载菜单项,下面的解析比较少用到)
	int nIdIndex = 100;
	TiXmlElement* pItemElem = NULL;
	for (pItemElem = pXmlElem->FirstChildElement("item"); pItemElem != NULL; pItemElem=pItemElem->NextSiblingElement())
	{
		CStringA strId = pItemElem->Attribute("id");
		int nId = nIdIndex;
		if(strId != "")
		{
			nId = atoi(strId);
		}

		CStringA strType = pItemElem->Attribute("type");
		CStringA strName = pItemElem->Attribute("name");
		CStringA strImage = pItemElem->Attribute("image");
		CStringA strTitle = pItemElem->Attribute("title");
		
		if(strType == "separator")
		{
			// 分隔线也可以用图片的方式
			AddSeparator();
			continue;
		}
		CString strTitleU = CA2T(strTitle, CP_UTF8);
		if(strImage.Find(".") != -1)	// 加载图片文件
		{
			CString strImgFile = CA2T(strImage, CP_UTF8);
			AddMenu(strTitleU, nIdIndex, strImgFile);
		}else
		if(!strImage.IsEmpty())
		{
			UINT nResourceID = atoi(strImage);
			AddMenu(strTitleU, nIdIndex, nResourceID);
		}else
		{
			AddMenu(strTitleU, nIdIndex);
		}

		nIdIndex++;
	}

	// 刷新各菜单控件的位置
	SetMenuPoint();

	m_bInit = TRUE;

    return TRUE;
}
bool CUrlSrcGetFromSvrSocket::ProcessHttpResponseBody_Start(const BYTE* pucData, UINT size)
{
	if (thePrefs.GetVerbose())
	{
		AddDebugLogLine(false, _T("Receive UrlSources from server (http response body)"));
		AddDebugLogLine(false, CString((const char*) pucData, size));
	}


	if (::IsBadReadPtr(m_pMgr, sizeof(CUrlSrcFromSvrMgr)))
		return true;

	CStringA	straLine;
	CString		strUrl;
	CString		strRefer;
	LPCSTR		p;
	LPCSTR		pcNl;
	int			iRemain;
	int			iLineLen;
	int			iIndexT;
	int			iSepLen;	//分隔符长度

	p = (LPCSTR) pucData;
	pcNl = NULL;
	iRemain = size;
	while (iRemain > 0)
	{
		pcNl = (LPCSTR) memchr(p, '\n', iRemain);
		if (NULL == pcNl)
		{
			iSepLen = 0;
			iLineLen = iRemain;
		}
		else
		{
			iSepLen = 1;

			if (pcNl > p							// 确保 (pcNl - 1) 可读
				&& *(pcNl - 1) == '\r')				//如果分隔符是“\r\n”,则分隔符长度为 2。
				iSepLen = 2;

			iLineLen = pcNl + 1 - p;
		}

		if (iLineLen <= 0)
			break;

		//	取出一行数据
		int iCopyStrLen = iLineLen - iSepLen;
		char *pCopy = new char[iCopyStrLen + 1];
		strncpy(pCopy, p, iCopyStrLen);
		pCopy[iCopyStrLen] = 0;

		straLine = pCopy;

		delete[] pCopy;
		pCopy = NULL;

		//	把指针移动到下一行
		p += iLineLen;
		iRemain -= iLineLen;

		//	把一行数据解析出来,并添加到列表中。
		iIndexT = straLine.Find('\t');
		if (-1 == iIndexT)
		{
			strUrl = straLine;
			strRefer.Empty();
		}
		else
		{
			strUrl = straLine.Left(iIndexT);
			strRefer = straLine.Mid(iIndexT + 1);
		}

		CStringW	strUrlW;
		strUrlW = strUrl;
		if (S_OK == ::IsValidURL(NULL, strUrlW, 0))
			m_pMgr->m_strlstFetchedUrlSources.AddTail(CString(straLine));	//把整行数据添加至列表,以保存Refer信息。
	}

	if (NULL != m_pMgr->m_pAssocPartFile)
		m_pMgr->m_pAssocPartFile->OnUrlSrcFromSvrFetched(&m_pMgr->m_strlstFetchedUrlSources);

	return true;
}
Esempio n. 15
0
BOOL CDCNeighbour::OnUserInfo(LPSTR szInfo)
{
	// User info
	// $MyINFO $ALL nick description<tag>$ $connection$e-mail$sharesize$|

	if ( strncmp( szInfo, _P("$ALL ") ) == 0 )
	{
		LPSTR szNick = szInfo + 5;
		if ( LPSTR szDescription = strchr( szNick, ' ' ) )
		{
			*szDescription++ = 0;

			CString sNick( UTF8Decode( szNick ) );

			CChatUser* pUser;
			if ( ! m_oUsers.Lookup( sNick, pUser ) )
			{
				pUser = new CChatUser;
				m_oUsers.SetAt( sNick, pUser );
			}
			pUser->m_bType = ( sNick == m_sNick ) ? cutMe : cutUser;
			pUser->m_sNick = sNick;

			if ( LPSTR szConnection = strchr( szDescription, '$' ) )
			{
				*szConnection++ = 0;

				if ( LPSTR szVendor = strchr( szDescription, '<' ) )
				{
					if ( *(szConnection - 2) == '>' )
					{
						*szVendor++ = 0;
						*(szConnection - 2) = 0;

						CStringA sVersion;
						if ( LPSTR szTags = strchr( szVendor, ' ' ) )
						{
							*szTags++ = 0;

							for ( CStringA sTags( szTags ); ! sTags.IsEmpty(); )
							{
								CStringA sTag = sTags.SpanExcluding( "," );
								sTags = sTags.Mid( sTag.GetLength() + 1 );
								if ( sTag.IsEmpty() )
									continue;
								int nPos = sTag.Find( ':' );
								if ( nPos > 0 )
								{
									CStringA sTagName = sTag.Left( nPos );
									sTag = sTag.Mid( nPos + 1 );

									if ( sTagName == "V" )
									{
										// Version

										sVersion = sTag;
									}
									else if ( sTagName == "M" )
									{
										// Mode
									}
									else if ( sTagName == "H" )
									{
										// Hubs
									}
									else if ( sTagName == "S" )
									{
										// Slots
									}
								}
							}
						}

						pUser->m_sUserAgent = UTF8Decode( szVendor );
						if ( ! sVersion.IsEmpty() )
							pUser->m_sUserAgent += _T(" ") + UTF8Decode( sVersion );
					}
				}
			}

			pUser->m_sDescription = UTF8Decode( szDescription );

			if ( m_nNodeType == ntHub )
			{
				HostCache.DC.Add( &m_pHost.sin_addr, htons( m_pHost.sin_port ), 0, 0, 0, GetUserCount() );
			}

			// Notify chat window
			ChatCore.OnAddUser( this, new CChatUser( *pUser ) );
		}
	}

	return TRUE;
}
Esempio n. 16
0
static bool fixLinks(CStringA& rtf, uidToTitleMap_t *uidToTitleMapPtr)
{
	// quick check, quick exit
	if (rtf.Find("\\lnkd\\protect") == -1)
		return false;

	int clrTableIndex = getColorTableIndex(rtf);
	if (clrTableIndex == -1)
	{
		// something bad happened
		return false;
	}

	// get code page
	unsigned codepage = CP_ACP;
	int cpgPos = rtf.Find("\\ansicpg");
	if (cpgPos != -1)
		codepage = atoi((LPCSTR)rtf + cpgPos + sizeof("\\ansicpg")-1);

	// for each pattern of 
	//		\lnkd\protect[<space>]<text>\protect0\lnkd0
	// replace with "out", where out is:
	//      sprintf(out, _linkRTF, <nodeurl>, clrTableIndex, <text>)
	// where <nodeurl> is:
	//		lookupNode(stripRTF(<text>))

	int pos, ofs = 0;
	while ( (pos = rtf.Find("\\lnkd\\protect", ofs)) != -1 )
	{
		// ofs2 points to start of text
		int ofs2 = pos + sizeof("\\lnkd\\protect")-1;

		// check if the \protect had a ' ' delimiter, eat it if so
		if (rtf[ofs2] == ' ')
			ofs2++;

		// locate the end tag
		int pos2 = rtf.Find("\\protect0\\lnkd0", ofs2);
		ASSERT(pos2 != -1);
		if (pos2 == -1)
			return false;

		// get the text inbetween
		// here is the link (title of page)..
		CStringA rtfLink = rtf.Mid(ofs2, pos2-ofs2);
		CString link = stripRTF(rtfLink, codepage);

		// look it up
		CStringA url;
		if (isURL(link))
		{
			// points to a URL itself (http://, https://, ftp:// etc..)
			url = escapeRTF(link);

			// There appears to be a strange bug with the rich edit control, in that if
			// the hyperlink and the text are exacly the same, the hyperlink effect goes
			// off. As a workaround, add a space after the URL (this is ignore in our
			// EN_LINK handler).
			url += " ";
		}
		else
		{
			uint32 nodeUid = 0;
			if (uidToTitleMapPtr->Lookup(link, nodeUid))
				// matched a node
				url.Format("node://./%u", nodeUid);
			else
				// unmatched node, we'll handle this later
				url.Format("oldlink://./%s", escapeRTF(link));
		}

		// make the replacement
		CStringA replacement;
		replacement.Format(_linkRTF, url, clrTableIndex, escapeRTF(link));

		// delete [pos, pos2+15]
		rtf.Delete(pos, pos2+15-pos);
		rtf.Insert(pos, replacement);

		// repositon to just after the replacement
		ofs = pos + replacement.GetLength();
	}

	return true;
}
Esempio n. 17
0
/**
 * カテゴリURLの移行処理
 *
 * カテゴリ名も変更可能(例:"みんなのecho" ⇒ "みんなのボイス")
 */
inline CString getNormalizedCategoryUrl(LPCTSTR default_category_url,
										CStringA category_url,
										ACCESS_TYPE category_type,
										std::string& category_name)
{

#ifdef BT_MZ3
	// 旧形式iniファイルの移行処理
	if (category_type == ACCESS_LIST_FOOTSTEP && category_url == "show_log.pl") {
		// 旧あしあとURLはAPI用URLに置換(デフォルトURLを採用する)
		return default_category_url;
	}

	/* 下記は「マイミク一覧」を "list_friend.pl" から API に移行したときの処理
	if (category_type == ACCESS_LIST_FRIEND && category_url == "list_friend.pl") {
		// 旧マイミク一覧URLはAPI用URLに置換(デフォルトURLを採用する)
		return default_category_url;
	}
	*/

	if (category_type == ACCESS_LIST_FRIEND) {
		// マイミク一覧URLはデフォルトURLが正しい("list_friend.pl" や API の URL は廃止とする)
		return default_category_url;
	}

	if (category_type == ACCESS_MIXI_RECENT_VOICE &&
		category_url.Find("recent_echo.pl")>=0)
	{
		// 移行処理:recent_echo.pl を recent_voice.pl に書き換える
		CString strCategoryUrl(category_url);
		strCategoryUrl.Replace(L"recent_echo.pl",
							   L"recent_voice.pl");
		category_name = "みんなのボイス";
		return strCategoryUrl;
	}
	
	if (category_type == ACCESS_MIXI_RECENT_VOICE &&
		category_url.Find("res_echo.pl")>=0 &&
		strstr(category_name.c_str(), "返信")!=NULL)
	{
		// 移行処理:res_voice.pl は 2010/04/14 のmixi仕様変更で消えたので項目としても削除
		return L"";
	}
#endif

	if (category_type == ACCESS_TWITTER_FRIENDS_TIMELINE) {
		// 移行処理:friends_timeline.xml => home_timeline.xml
		if (category_url.Find("http://twitter.com/statuses/friends_timeline.xml")>=0) {
			category_url.Replace("http://twitter.com/statuses/friends_timeline.xml",
								 "http://api.twitter.com/1/statuses/home_timeline.xml");
			return CString(category_url);
		}

		// 移行処理:home_timeline.xml (BASIC認証用) => api 用 URL
		if (category_url.Find("http://twitter.com/statuses/home_timeline.xml")>=0) {
			category_url.Replace("http://twitter.com/statuses/home_timeline.xml",
								 "http://api.twitter.com/1/statuses/home_timeline.xml");
			return CString(category_url);
		}
	}

	return CString(category_url);
}
Esempio n. 18
0
HRESULT CMatroskaSplitterFilter::CreateOutputs(IAsyncReader* pAsyncReader)
{
	CheckPointer(pAsyncReader, E_POINTER);

	HRESULT hr = E_FAIL;

	m_pFile.Free();
	m_pTrackEntryMap.RemoveAll();
	m_pOrderedTrackArray.RemoveAll();

	CAtlArray<CMatroskaSplitterOutputPin*> pinOut;
	CAtlArray<TrackEntry*> pinOutTE;

	m_pFile.Attach(DNew CMatroskaFile(pAsyncReader, hr));
	if(!m_pFile) return E_OUTOFMEMORY;
	if(FAILED(hr)) {m_pFile.Free(); return hr;}

	m_rtNewStart = m_rtCurrent = 0;
	m_rtNewStop = m_rtStop = m_rtDuration = 0;

	int iVideo = 1, iAudio = 1, iSubtitle = 1;

	POSITION pos = m_pFile->m_segment.Tracks.GetHeadPosition();
	while(pos)
	{
		Track* pT = m_pFile->m_segment.Tracks.GetNext(pos);

		POSITION pos2 = pT->TrackEntries.GetHeadPosition();
		while(pos2)
		{
			TrackEntry* pTE = pT->TrackEntries.GetNext(pos2);

			bool isSub = false;

			if(!pTE->Expand(pTE->CodecPrivate, ContentEncoding::TracksPrivateData))
				continue;

			CStringA CodecID = pTE->CodecID.ToString();

			CStringW Name;
			Name.Format(L"Output %I64d", (UINT64)pTE->TrackNumber);

			CMediaType mt;
			CAtlArray<CMediaType> mts;

			mt.SetSampleSize(1);

			if(pTE->TrackType == TrackEntry::TypeVideo)
			{
				Name.Format(L"Video %d", iVideo++);

				mt.majortype = MEDIATYPE_Video;

				if(CodecID == "V_MS/VFW/FOURCC")
				{
					mt.formattype = FORMAT_VideoInfo;
					VIDEOINFOHEADER* pvih = (VIDEOINFOHEADER*)mt.AllocFormatBuffer(sizeof(VIDEOINFOHEADER) + pTE->CodecPrivate.GetCount() - sizeof(BITMAPINFOHEADER));
					memset(mt.Format(), 0, mt.FormatLength());
					memcpy(&pvih->bmiHeader, pTE->CodecPrivate.GetData(), pTE->CodecPrivate.GetCount());
					mt.subtype = FOURCCMap(pvih->bmiHeader.biCompression);
					switch(pvih->bmiHeader.biCompression)
					{
					case BI_RGB: case BI_BITFIELDS: mt.subtype = 
						pvih->bmiHeader.biBitCount == 1 ? MEDIASUBTYPE_RGB1 :
						pvih->bmiHeader.biBitCount == 4 ? MEDIASUBTYPE_RGB4 :
						pvih->bmiHeader.biBitCount == 8 ? MEDIASUBTYPE_RGB8 :
						pvih->bmiHeader.biBitCount == 16 ? MEDIASUBTYPE_RGB565 :
						pvih->bmiHeader.biBitCount == 24 ? MEDIASUBTYPE_RGB24 :
						pvih->bmiHeader.biBitCount == 32 ? MEDIASUBTYPE_ARGB32 :
						MEDIASUBTYPE_NULL;
						break;
//					case BI_RLE8: mt.subtype = MEDIASUBTYPE_RGB8; break;
//					case BI_RLE4: mt.subtype = MEDIASUBTYPE_RGB4; break;
					}
					mts.Add(mt);
				}
				else if(CodecID == "V_UNCOMPRESSED")
				{
				}
				else if(CodecID.Find("V_MPEG4/ISO/AVC") == 0 && pTE->CodecPrivate.GetCount() >= 6)
				{
					BYTE sps = pTE->CodecPrivate[5] & 0x1f;

	std::vector<BYTE> avcC;
	for(int i = 0, j = pTE->CodecPrivate.GetCount(); i < j; i++)
		avcC.push_back(pTE->CodecPrivate[i]);

	std::vector<BYTE> sh;

	unsigned jj = 6;

	while (sps--) {
	  if (jj + 2 > avcC.size())
	    goto avcfail;
	  unsigned spslen = ((unsigned)avcC[jj] << 8) | avcC[jj+1];
	  if (jj + 2 + spslen > avcC.size())
	    goto avcfail;
	  unsigned cur = sh.size();
	  sh.resize(cur + spslen + 2, 0);
	  std::copy(avcC.begin() + jj, avcC.begin() + jj + 2 + spslen,sh.begin() + cur);
	  jj += 2 + spslen;
	}

	if (jj + 1 > avcC.size())
	  continue;

	unsigned pps = avcC[jj++];

	while (pps--) {
	  if (jj + 2 > avcC.size())
	    goto avcfail;
	  unsigned ppslen = ((unsigned)avcC[jj] << 8) | avcC[jj+1];
	  if (jj + 2 + ppslen > avcC.size())
	    goto avcfail;
	  unsigned cur = sh.size();
	  sh.resize(cur + ppslen + 2, 0);
	  std::copy(avcC.begin() + jj, avcC.begin() + jj + 2 + ppslen, sh.begin() + cur);
	  jj += 2 + ppslen;
	}

	goto avcsuccess;
avcfail:
	continue;
avcsuccess:

					CAtlArray<BYTE> data;
					data.SetCount(sh.size());
					std::copy(sh.begin(), sh.end(), data.GetData());

					mt.subtype = FOURCCMap('1CVA');
					mt.formattype = FORMAT_MPEG2Video;
					MPEG2VIDEOINFO* pm2vi = (MPEG2VIDEOINFO*)mt.AllocFormatBuffer(FIELD_OFFSET(MPEG2VIDEOINFO, dwSequenceHeader) + data.GetCount());
					memset(mt.Format(), 0, mt.FormatLength());
					pm2vi->hdr.bmiHeader.biSize = sizeof(pm2vi->hdr.bmiHeader);
					pm2vi->hdr.bmiHeader.biWidth = (LONG)pTE->v.PixelWidth;
					pm2vi->hdr.bmiHeader.biHeight = (LONG)pTE->v.PixelHeight;
					pm2vi->hdr.bmiHeader.biCompression = '1CVA';
					pm2vi->hdr.bmiHeader.biPlanes = 1;
					pm2vi->hdr.bmiHeader.biBitCount = 24;
					pm2vi->dwProfile = pTE->CodecPrivate[1];
					pm2vi->dwLevel = pTE->CodecPrivate[3];
					pm2vi->dwFlags = (pTE->CodecPrivate[4] & 3) + 1;
					BYTE* pSequenceHeader = (BYTE*)pm2vi->dwSequenceHeader;
					memcpy(pSequenceHeader, data.GetData(), data.GetCount());
					pm2vi->cbSequenceHeader = data.GetCount();
					mts.Add(mt);
				}
				else if(CodecID.Find("V_MPEG4/") == 0)
				{
					mt.subtype = FOURCCMap('V4PM');
					mt.formattype = FORMAT_MPEG2Video;
					MPEG2VIDEOINFO* pm2vi = (MPEG2VIDEOINFO*)mt.AllocFormatBuffer(FIELD_OFFSET(MPEG2VIDEOINFO, dwSequenceHeader) + pTE->CodecPrivate.GetCount());
					memset(mt.Format(), 0, mt.FormatLength());
					pm2vi->hdr.bmiHeader.biSize = sizeof(pm2vi->hdr.bmiHeader);
					pm2vi->hdr.bmiHeader.biWidth = (LONG)pTE->v.PixelWidth;
					pm2vi->hdr.bmiHeader.biHeight = (LONG)pTE->v.PixelHeight;
					pm2vi->hdr.bmiHeader.biCompression = 'V4PM';
					pm2vi->hdr.bmiHeader.biPlanes = 1;
					pm2vi->hdr.bmiHeader.biBitCount = 24;
					BYTE* pSequenceHeader = (BYTE*)pm2vi->dwSequenceHeader;
					memcpy(pSequenceHeader, pTE->CodecPrivate.GetData(), pTE->CodecPrivate.GetCount());
					pm2vi->cbSequenceHeader = pTE->CodecPrivate.GetCount();
					mts.Add(mt);
				}
				else if(CodecID.Find("V_REAL/RV") == 0)
				{
					mt.subtype = FOURCCMap('00VR' + ((CodecID[9]-0x30)<<16));
					mt.formattype = FORMAT_VideoInfo;
					VIDEOINFOHEADER* pvih = (VIDEOINFOHEADER*)mt.AllocFormatBuffer(sizeof(VIDEOINFOHEADER) + pTE->CodecPrivate.GetCount());
					memset(mt.Format(), 0, mt.FormatLength());
					memcpy(mt.Format() + sizeof(VIDEOINFOHEADER), pTE->CodecPrivate.GetData(), pTE->CodecPrivate.GetCount());
					pvih->bmiHeader.biSize = sizeof(pvih->bmiHeader);
					pvih->bmiHeader.biWidth = (LONG)pTE->v.PixelWidth;
					pvih->bmiHeader.biHeight = (LONG)pTE->v.PixelHeight;
					pvih->bmiHeader.biCompression = mt.subtype.Data1;
					mts.Add(mt);
				}
				else if(CodecID == "V_DIRAC")
				{
					mt.subtype = MEDIASUBTYPE_DiracVideo;
					mt.formattype = FORMAT_DiracVideoInfo;
					DIRACINFOHEADER* dvih = (DIRACINFOHEADER*)mt.AllocFormatBuffer(FIELD_OFFSET(DIRACINFOHEADER, dwSequenceHeader) + pTE->CodecPrivate.GetCount());
					memset(mt.Format(), 0, mt.FormatLength());
					dvih->hdr.bmiHeader.biSize = sizeof(dvih->hdr.bmiHeader);
					dvih->hdr.bmiHeader.biWidth = (LONG)pTE->v.PixelWidth;
					dvih->hdr.bmiHeader.biHeight = (LONG)pTE->v.PixelHeight;
					dvih->hdr.dwPictAspectRatioX = dvih->hdr.bmiHeader.biWidth;
					dvih->hdr.dwPictAspectRatioY = dvih->hdr.bmiHeader.biHeight;

					BYTE* pSequenceHeader = (BYTE*)dvih->dwSequenceHeader;
					memcpy(pSequenceHeader, pTE->CodecPrivate.GetData(), pTE->CodecPrivate.GetCount());
					dvih->cbSequenceHeader = pTE->CodecPrivate.GetCount();

					mts.Add(mt);
				}
				else if(CodecID == "V_MPEG2")
				{
					BYTE* seqhdr = pTE->CodecPrivate.GetData();
					DWORD len = pTE->CodecPrivate.GetCount();
					int w = pTE->v.PixelWidth;
					int h = pTE->v.PixelHeight;

					if(MakeMPEG2MediaType(mt, seqhdr, len, w, h))
						mts.Add(mt);
				}
				else if(CodecID == "V_THEORA")
				{
					BYTE* thdr = pTE->CodecPrivate.GetData() + 3;

					mt.majortype		= MEDIATYPE_Video;
					mt.subtype			= FOURCCMap('OEHT');
					mt.formattype		= FORMAT_MPEG2_VIDEO;
					MPEG2VIDEOINFO* vih = (MPEG2VIDEOINFO*)mt.AllocFormatBuffer(sizeof(MPEG2VIDEOINFO) + pTE->CodecPrivate.GetCount());
					memset(mt.Format(), 0, mt.FormatLength());
					vih->hdr.bmiHeader.biSize		 = sizeof(vih->hdr.bmiHeader);
					vih->hdr.bmiHeader.biWidth		 = *(WORD*)&thdr[10] >> 4;
					vih->hdr.bmiHeader.biHeight		 = *(WORD*)&thdr[12] >> 4;
					vih->hdr.bmiHeader.biCompression = 'OEHT';
					vih->hdr.bmiHeader.biPlanes		 = 1;
					vih->hdr.bmiHeader.biBitCount	 = 24;
					int nFpsNum	= (thdr[22]<<24)|(thdr[23]<<16)|(thdr[24]<<8)|thdr[25];
					int nFpsDenum	= (thdr[26]<<24)|(thdr[27]<<16)|(thdr[28]<<8)|thdr[29];
					if(nFpsNum) vih->hdr.AvgTimePerFrame = (REFERENCE_TIME)(10000000.0 * nFpsDenum / nFpsNum);
					vih->hdr.dwPictAspectRatioX = (thdr[14]<<16)|(thdr[15]<<8)|thdr[16];
					vih->hdr.dwPictAspectRatioY = (thdr[17]<<16)|(thdr[18]<<8)|thdr[19];
					mt.bFixedSizeSamples = 0;

					vih->cbSequenceHeader = pTE->CodecPrivate.GetCount();
					memcpy (&vih->dwSequenceHeader, pTE->CodecPrivate.GetData(), vih->cbSequenceHeader);

					mts.Add(mt);
				}
				else if(CodecID.Find("V_VP8") == 0) 
				{ 
					mt.subtype = FOURCCMap('08PV'); 
					mt.formattype = FORMAT_VideoInfo; 
					VIDEOINFOHEADER* pvih = (VIDEOINFOHEADER*)mt.AllocFormatBuffer(sizeof(VIDEOINFOHEADER) + pTE->CodecPrivate.GetCount()); 
					memset(mt.Format(), 0, mt.FormatLength()); 
					memcpy(mt.Format() + sizeof(VIDEOINFOHEADER), pTE->CodecPrivate.GetData(), pTE->CodecPrivate.GetCount()); 
					pvih->bmiHeader.biSize = sizeof(pvih->bmiHeader); 
					pvih->bmiHeader.biWidth = (LONG)pTE->v.PixelWidth; 
					pvih->bmiHeader.biHeight = (LONG)pTE->v.PixelHeight; 
					pvih->bmiHeader.biCompression = mt.subtype.Data1; 
					mts.Add(mt); 
				} 
/*
				else if(CodecID == "V_DSHOW/MPEG1VIDEO") // V_MPEG1
				{
					mt.majortype = MEDIATYPE_Video;
					mt.subtype = MEDIASUBTYPE_MPEG1Payload;
					mt.formattype = FORMAT_MPEGVideo;
					MPEG1VIDEOINFO* pm1vi = (MPEG1VIDEOINFO*)mt.AllocFormatBuffer(pTE->CodecPrivate.GetCount());
					memcpy(pm1vi, pTE->CodecPrivate.GetData(), pTE->CodecPrivate.GetCount());
					mt.SetSampleSize(pm1vi->hdr.bmiHeader.biWidth*pm1vi->hdr.bmiHeader.biHeight*4);
					mts.Add(mt);
				}
*/
				REFERENCE_TIME AvgTimePerFrame = 0;

                if(pTE->v.FramePerSec > 0)
					AvgTimePerFrame = (REFERENCE_TIME)(10000000i64 / pTE->v.FramePerSec);
				else if(pTE->DefaultDuration > 0)
					AvgTimePerFrame = (REFERENCE_TIME)pTE->DefaultDuration / 100;

				if(AvgTimePerFrame)
				{
					for(int i = 0; i < mts.GetCount(); i++)
					{
						if(mts[i].formattype == FORMAT_VideoInfo
						|| mts[i].formattype == FORMAT_VideoInfo2
						|| mts[i].formattype == FORMAT_MPEG2Video)
						{
							((VIDEOINFOHEADER*)mts[i].Format())->AvgTimePerFrame = AvgTimePerFrame;
						}
					}
				}

				if(pTE->v.DisplayWidth != 0 && pTE->v.DisplayHeight != 0)
				{
					for(int i = 0; i < mts.GetCount(); i++)
					{
						if(mts[i].formattype == FORMAT_VideoInfo)
						{
							DWORD vih1 = FIELD_OFFSET(VIDEOINFOHEADER, bmiHeader);
							DWORD vih2 = FIELD_OFFSET(VIDEOINFOHEADER2, bmiHeader);
							DWORD bmi = mts[i].FormatLength() - FIELD_OFFSET(VIDEOINFOHEADER, bmiHeader);
							mt.formattype = FORMAT_VideoInfo2;
							mt.AllocFormatBuffer(vih2 + bmi);
							memcpy(mt.Format(), mts[i].Format(), vih1);
							memset(mt.Format() + vih1, 0, vih2 - vih1);
							memcpy(mt.Format() + vih2, mts[i].Format() + vih1, bmi);
							((VIDEOINFOHEADER2*)mt.Format())->dwPictAspectRatioX = (DWORD)pTE->v.DisplayWidth;
							((VIDEOINFOHEADER2*)mt.Format())->dwPictAspectRatioY = (DWORD)pTE->v.DisplayHeight;
							mts.InsertAt(i++, mt);
						}
						else if(mts[i].formattype == FORMAT_MPEG2Video)
						{
							((MPEG2VIDEOINFO*)mts[i].Format())->hdr.dwPictAspectRatioX = (DWORD)pTE->v.DisplayWidth;
							((MPEG2VIDEOINFO*)mts[i].Format())->hdr.dwPictAspectRatioY = (DWORD)pTE->v.DisplayHeight;
						}
					}
				}
			}
Esempio n. 19
0
void CProgressDlg::ParserCmdOutput(CRichEditCtrl &log,CProgressCtrl &progressctrl,HWND m_hWnd,CComPtr<ITaskbarList3> m_pTaskbarList,CStringA &oneline, char ch, CWnd *CurrentWork)
{
	//TRACE(_T("%c"),ch);
	if( ch == ('\r') || ch == ('\n'))
	{
		CString str;

//		TRACE(_T("End Char %s \r\n"),ch==_T('\r')?_T("lf"):_T(""));
//		TRACE(_T("End Char %s \r\n"),ch==_T('\n')?_T("cr"):_T(""));

		if(ClearESC(oneline))
		{
			ch = ('\r');
		}

		int lines = log.GetLineCount();
		g_Git.StringAppend(&str,(BYTE*)oneline.GetBuffer(),CP_ACP);
		str.Trim();
//		TRACE(_T("%s"), str);

		if(ch == ('\r'))
		{
			int start=log.LineIndex(lines-1);
			log.SetSel(start, log.GetTextLength());
			log.ReplaceSel(str);
		}
		else
		{
			int length = log.GetWindowTextLength();
			log.SetSel(length, length);
			if (length > 0)
				log.ReplaceSel(_T("\r\n") + str);
			else
				log.ReplaceSel(str);
		}

		if (lines > 500) //limited log length
		{
			int end=log.LineIndex(1);
			log.SetSel(0,end);
			log.ReplaceSel(_T(""));
		}
		log.LineScroll(log.GetLineCount() - log.GetFirstVisibleLine() - 4);

		int s1=oneline.ReverseFind(_T(':'));
		int s2=oneline.Find(_T('%'));
		if (s1 > 0 && s2 > 0)
		{
			if(CurrentWork)
				CurrentWork->SetWindowTextW(str.Left(s1));

			int pos=FindPercentage(str);
			TRACE(_T("Pos %d\r\n"),pos);
			if(pos>0)
			{
				progressctrl.SetPos(pos);
				if (m_pTaskbarList)
				{
					m_pTaskbarList->SetProgressState(m_hWnd, TBPF_NORMAL);
					m_pTaskbarList->SetProgressValue(m_hWnd, pos, 100);
				}
			}
		}

		oneline="";

	}
	else
	{
		oneline+=ch;
	}
}
Esempio n. 20
0
BOOL CSNMP::SnmpQueryTable( LPCTSTR apColumnOidList[], UINT nListLen, std::vector<std::pair<CString, std::vector<AsnAny>>> *pTable )
{
	if (!apColumnOidList || !pTable)
	{
		m_strLastError = L"[SnmpQueryTable] : Verify the arguments failed. ";
		return FALSE;
	}

	pTable->clear();

	if (!nListLen)
		return TRUE;

	typedef std::map<CString, AsnAny> RELATIVE_OID_TO_VALUE_MAP;

	std::vector<RELATIVE_OID_TO_VALUE_MAP> vColumnRelativeOidToValue(nListLen);

	SnmpVarBindList CurrentVarBindList;
	CurrentVarBindList.len = 0;
	CurrentVarBindList.list = NULL;

	AsnObjectIdentifier TargetObjectIdentifier;
	TargetObjectIdentifier.idLength = 0;
	TargetObjectIdentifier.ids = NULL;

	BOOL bRes = FALSE;
	do 
	{
		UINT i = 0;
		for (; i < nListLen; i++)
		{
			SnmpUtilVarBindListFree(&CurrentVarBindList);

			CurrentVarBindList.len = 1;
			CurrentVarBindList.list = (SnmpVarBind *)SnmpUtilMemAlloc(sizeof(SnmpVarBind));
			CurrentVarBindList.list->name.idLength = 0;
			CurrentVarBindList.list->name.ids = NULL;
			CurrentVarBindList.list->value.asnType = ASN_NULL;

#ifdef _UNICODE
			CStringA strOIDA = XLibS::StringCode::ConvertWideStrToAnsiStr(apColumnOidList[i]); 
#else
			CStringA strOIDA = apColumnOidList[i];
#endif

			if(!::SnmpMgrStrToOid(strOIDA.GetBuffer(), &CurrentVarBindList.list->name) || !CurrentVarBindList.list->name.ids || !CurrentVarBindList.list->name.idLength)
			{

#ifdef _UNICODE
				CStringW strOIDW = apColumnOidList[i];
#else
				CStringW strOIDW = XLibS::StringCode::ConvertAnsiStrToWideStr(apColumnOidList[i]);
#endif
				m_strLastError.Format(L"[SnmpQueryTable] : Bad OID string \"%s\". ", (LPCWSTR)strOIDW);

				strOIDA.ReleaseBuffer();

				break;
			}
			strOIDA.ReleaseBuffer();

			SnmpUtilOidFree(&TargetObjectIdentifier);
			TargetObjectIdentifier.idLength = 0;
			TargetObjectIdentifier.ids = NULL;

			if (!SnmpUtilOidCpy(&TargetObjectIdentifier, &CurrentVarBindList.list->name) || !TargetObjectIdentifier.ids || !TargetObjectIdentifier.idLength)
			{
				m_strLastError.Format(L"[SnmpQueryTable] : Copy OID failed. ");
				break;
			}

			BOOL bFailFlag = FALSE;
			while(1)
			{
				AsnInteger nSNMPErrorCode = 0;
				AsnInteger nSNMPErrorIndex = 0;
				if(!::SnmpMgrRequest(m_SnmpSession, SNMP_PDU_GETNEXT, &CurrentVarBindList, &nSNMPErrorCode, &nSNMPErrorIndex))
				{
					DWORD dwLastWinError = ::GetLastError();
					assert(nSNMPErrorIndex == 0);

					const WCHAR * SNMP_ERROR_MESSAGE[] = { L"The agent reports that no errors occurred during transmission. ", 
						L"The agent could not place the results of the requested operation into a single SNMP message. ", 
						L"The requested operation identified an unknown variable. ", 
						L"The requested operation tried to change a variable but it specified either a syntax or value error. ", 
						L"The requested operation tried to change a variable that was not allowed to change according to the community profile of the variable. "
					};

					const WCHAR * WIN_ERROR_MESSAGE[] = {L"The request timed-out.",
						L"Unexpected error file descriptors indicated by the Windows Sockets select function."
					};

					const WCHAR *pSNMPError = NULL;
					if (nSNMPErrorIndex < ARRAYSIZE(SNMP_ERROR_MESSAGE))
						pSNMPError = SNMP_ERROR_MESSAGE[nSNMPErrorIndex];
					else
						pSNMPError = L"Unknown error. ";

					const WCHAR *pWinError = NULL;
					if (dwLastWinError - 40 < ARRAYSIZE(WIN_ERROR_MESSAGE))
						pWinError = WIN_ERROR_MESSAGE[dwLastWinError - 40];
					else
						pWinError = L"Unknown error. ";

					m_strLastError.Format(L"SNMP requesting failed. SNMP ERROR : %s (%ld). WIN ERROR : %s (%lu). ", 
						pSNMPError, nSNMPErrorIndex, pWinError, dwLastWinError);
	
//					LPCWSTR pSysError = NULL;
//					m_strLastError.Format(L"SNMP requesting failed. SNMP ERROR : %s (%ld). ", pError, nErrorIndex);
//					if (::FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, 
//						NULL, dwLastError, 0, (LPTSTR)&pSysError, 0, NULL) && pSysError)
//					{
//						m_strLastError.AppendFormat(L"Windows ERROR: %s (%lu). ", pSysError, dwLastError);
//
//						::LocalFree((HLOCAL)pSysError);
//						pSysError = NULL;
//					}

					
					bFailFlag = TRUE;
					break;
				}

				assert(SNMP_ERRORSTATUS_NOERROR == nSNMPErrorCode);
				
				if (!CurrentVarBindList.list || (!CurrentVarBindList.list->name.ids && CurrentVarBindList.list->name.idLength))
				{
#ifdef _UNICODE
					CStringW strOIDW = apColumnOidList[i];
#else
					CStringW strOIDW = XLibS::StringCode::ConvertAnsiStrToWideStr(apColumnOidList[i]);
#endif
					m_strLastError.Format(L"[SnmpQueryTable] : GetNext returned a bad OID during the request for %s. ", (LPCWSTR)strOIDW);

					bFailFlag = TRUE;
					break;
				}

				if (CurrentVarBindList.list->name.idLength < TargetObjectIdentifier.idLength)
					break;

				if (SnmpUtilOidNCmp(&CurrentVarBindList.list->name, &TargetObjectIdentifier, TargetObjectIdentifier.idLength))
					break;

				CStringA strOIDTarget = ThreadSafeSnmpUtilOidToA(&TargetObjectIdentifier);
				CStringA strOIDCurrent = ThreadSafeSnmpUtilOidToA(&CurrentVarBindList.list->name);

				assert(strOIDCurrent.Find(strOIDTarget) == 0);



				AsnAny value;
				SnmpUtilAsnAnyCpy(&value, &CurrentVarBindList.list->value);

#ifdef _UNICODE
				CString strRelativeOID = 
					XLibS::StringCode::ConvertAnsiStrToWideStr(strOIDCurrent.Mid(strOIDTarget.GetLength()));
#else
				CString strRelativeOID = strOIDCurrent.Mid(strOIDTarget.GetLength());
#endif

				vColumnRelativeOidToValue[i].insert(std::make_pair(strRelativeOID, value));
			}
			if (bFailFlag)
				break;

		}

		if (i < nListLen)
			break;

		const RELATIVE_OID_TO_VALUE_MAP & FirstCol = vColumnRelativeOidToValue[0];
		for (RELATIVE_OID_TO_VALUE_MAP::const_iterator itFirstCol = FirstCol.begin();
			itFirstCol != FirstCol.end(); itFirstCol++)
		{
			std::vector<RELATIVE_OID_TO_VALUE_MAP::const_iterator> vItFind;

			UINT i = 1;
			for (; i < nListLen; i++)
			{
				const RELATIVE_OID_TO_VALUE_MAP & CurrentCol = 
					vColumnRelativeOidToValue[i];

				RELATIVE_OID_TO_VALUE_MAP::const_iterator itFind =
					 CurrentCol.find(itFirstCol->first);

				if (itFind == CurrentCol.end())
					break;

				vItFind.push_back(itFind);
			}

			if (i < nListLen)
				continue;

			pTable->push_back(make_pair(itFirstCol->first, std::vector<AsnAny>(1, itFirstCol->second)));

			for (std::vector<RELATIVE_OID_TO_VALUE_MAP::const_iterator>::size_type i = 0;
				i < vItFind.size(); i++)
			{
				pTable->back().second.push_back(vItFind[i]->second);
			}
		}

		bRes = TRUE;

	} while (FALSE);

	SnmpUtilOidFree(&TargetObjectIdentifier);
	SnmpUtilVarBindListFree(&CurrentVarBindList);

	if (!bRes)
	{
		ClearQueryTableResult(*pTable);
		pTable->clear();
	}

	return bRes;
}
Esempio n. 21
0
void CWebServer::OnRequest(CWebClientSocket* pClient, CStringA& hdr, CStringA& body)
{
    CPath p(AToT(pClient->m_path));
    CStringA ext = p.GetExtension().MakeLower();
    CStringA mime;
    if (ext.IsEmpty()) {
        mime = "text/html";
    } else {
        m_mimes.Lookup(ext, mime);
    }

    hdr = "HTTP/1.0 200 OK\r\n";

    bool fHandled = false, fCGI = false;

    if (!fHandled && m_webroot.IsDirectory()) {
        CStringA tmphdr;
        fHandled = fCGI = CallCGI(pClient, tmphdr, body, mime);

        if (fHandled) {
            tmphdr.Replace("\r\n", "\n");
            CAtlList<CStringA> hdrlines;
            ExplodeMin(tmphdr, hdrlines, '\n');
            POSITION pos = hdrlines.GetHeadPosition();
            while (pos) {
                POSITION cur = pos;
                CAtlList<CStringA> sl;
                CStringA key = Explode(hdrlines.GetNext(pos), sl, ':', 2);
                if (sl.GetCount() < 2) {
                    continue;
                }
                key.Trim().MakeLower();
                if (key == "content-type") {
                    mime = sl.GetTail().Trim();
                    hdrlines.RemoveAt(cur);
                } else if (key == "content-length") {
                    hdrlines.RemoveAt(cur);
                }
            }
            tmphdr = Implode(hdrlines, "\r\n");
            hdr += tmphdr + "\r\n";
        }
    }

    RequestHandler rh = NULL;
    if (!fHandled && m_internalpages.Lookup(pClient->m_path, rh) && (pClient->*rh)(hdr, body, mime)) {
        if (mime.IsEmpty()) {
            mime = "text/html";
        }

        CString redir;
        if (pClient->m_get.Lookup("redir", redir)
                || pClient->m_post.Lookup("redir", redir)) {
            if (redir.IsEmpty()) {
                redir = '/';
            }

            hdr =
                "HTTP/1.0 302 Found\r\n"
                "Location: " + CStringA(redir) + "\r\n";
            return;
        }

        fHandled = true;
    }

    if (!fHandled && m_webroot.IsDirectory()) {
        fHandled = LoadPage(0, body, UTF8To16(pClient->m_path));
    }

    UINT resid;
    if (!fHandled && m_downloads.Lookup(pClient->m_path, resid)
            && (LoadResource(resid, body, _T("FILE")) || LoadResource(resid, body, _T("PNG")))) {
        if (mime.IsEmpty()) {
            mime = "application/octet-stream";
        }
        fHandled = true;
    }

    if (!fHandled) {
        hdr = mime == "text/html"
              ? "HTTP/1.0 301 Moved Permanently\r\n" "Location: /404.html\r\n"
              : "HTTP/1.0 404 Not Found\r\n";
        return;
    }

    if ((mime == "text/html" || mime == "text/javascript") && !fCGI) {
        if (mime == "text/html") {
            hdr +=
                "Expires: Thu, 19 Nov 1981 08:52:00 GMT\r\n"
                "Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0\r\n"
                "Pragma: no-cache\r\n";

            CStringA debug;
            if (AfxGetAppSettings().fWebServerPrintDebugInfo) {
                debug += "<br><hr>\r\n";
                debug += "<div id=\"debug\">";

                CStringA key;
                POSITION pos;

                {
                    CStringA value;

                    pos = pClient->m_hdrlines.GetStartPosition();
                    while (pos) {
                        pClient->m_hdrlines.GetNextAssoc(pos, key, value);
                        debug += "HEADER[" + key + "] = " + value + "\r\n";
                    }
                }
                debug += "cmd: " + pClient->m_cmd + "\r\n";
                debug += "path: " + pClient->m_path + "\r\n";
                debug += "ver: " + pClient->m_ver + "\r\n";

                {
                    CString value;

                    pos = pClient->m_get.GetStartPosition();
                    while (pos) {
                        pClient->m_get.GetNextAssoc(pos, key, value);
                        debug += "GET[" + HtmlSpecialChars(key) + "] = " + HtmlSpecialChars(UTF8(value)) + "\r\n";
                    }
                    pos = pClient->m_post.GetStartPosition();
                    while (pos) {
                        pClient->m_post.GetNextAssoc(pos, key, value);
                        debug += "POST[" + HtmlSpecialChars(key) + "] = " + HtmlSpecialChars(UTF8(value)) + "\r\n";
                    }
                    pos = pClient->m_cookie.GetStartPosition();
                    while (pos) {
                        pClient->m_cookie.GetNextAssoc(pos, key, value);
                        debug += "COOKIE[" + HtmlSpecialChars(key) + "] = " + HtmlSpecialChars(UTF8(value)) + "\r\n";
                    }
                    pos = pClient->m_request.GetStartPosition();
                    while (pos) {
                        pClient->m_request.GetNextAssoc(pos, key, value);
                        debug += "REQUEST[" + HtmlSpecialChars(key) + "] = " + HtmlSpecialChars(UTF8(value)) + "\r\n";
                    }
                }
                debug += "</div>";
            }
            body.Replace("[debug]", debug);
        }

        body.Replace("[browserpath]", "/browser.html");
        body.Replace("[commandpath]", "/command.html");
        body.Replace("[controlspath]", "/controls.html");
        body.Replace("[indexpath]", "/index.html");
        body.Replace("[path]", pClient->m_path);
        body.Replace("[setposcommand]", CMD_SETPOS);
        body.Replace("[setvolumecommand]", CMD_SETVOLUME);
        body.Replace("[wmcname]", "wm_command");
        // TODO: add more general tags to replace
    }

    // gzip
    if (AfxGetAppSettings().fWebServerUseCompression && !body.IsEmpty()
            && hdr.Find("Content-Encoding:") < 0 && ext != ".png" && ext != ".jpeg" && ext != ".gif")
        do {
            CStringA accept_encoding;
            pClient->m_hdrlines.Lookup("accept-encoding", accept_encoding);
            accept_encoding.MakeLower();
            CAtlList<CStringA> sl;
            ExplodeMin(accept_encoding, sl, ',');
            if (!sl.Find("gzip")) {
                break;
            }

            // Allocate deflate state
            z_stream strm;

            strm.zalloc = Z_NULL;
            strm.zfree = Z_NULL;
            strm.opaque = Z_NULL;
            int ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 15 + 16, 8, Z_DEFAULT_STRATEGY);
            if (ret != Z_OK) {
                ASSERT(0);
                break;
            }

            int gzippedBuffLen = body.GetLength();
            BYTE* gzippedBuff = DEBUG_NEW BYTE[gzippedBuffLen];

            // Compress
            strm.avail_in = body.GetLength();
            strm.next_in = (Bytef*)(LPCSTR)body;

            strm.avail_out = gzippedBuffLen;
            strm.next_out = gzippedBuff;

            ret = deflate(&strm, Z_FINISH);
            if (ret != Z_STREAM_END || strm.avail_in != 0) {
                ASSERT(0);
                deflateEnd(&strm);
                delete [] gzippedBuff;
                break;
            }
            gzippedBuffLen -= strm.avail_out;
            memcpy(body.GetBufferSetLength(gzippedBuffLen), gzippedBuff, gzippedBuffLen);

            // Clean up
            deflateEnd(&strm);
            delete [] gzippedBuff;

            hdr += "Content-Encoding: gzip\r\n";
        } while (0);

    CStringA content;
    content.Format(
        "Content-Type: %s\r\n"
        "Content-Length: %d\r\n",
        mime, body.GetLength());
    hdr += content;
}
Esempio n. 22
0
BOOL COSMCtrlMapOperationsDlg::ForceMapnikRerenderHelper()
{
  //Validate our parameters
  AFXASSUME(m_pOSMCtrl);

  //What will be the return value from this function (assume the best)
  BOOL bSuccess = TRUE;

  //Next get the server to connect to
  COSMCtrlMapnikTileProvider MapnikTileProvider;
  CString sServer(MapnikTileProvider.GetDownloadServer());

  //Accumulate how many tiles we have request to rerender and which ones indicated a failure to rerender
  int nTilesRerendered = 0;
  int nTilesNotRerendered = 0;

  //Next create the Wininet session object
  ASSERT(m_hSession == NULL);
  HRESULT hr = m_pOSMCtrl->CreateSession(m_hSession);
  if (SUCCEEDED(hr))
  {
    //Now create the connection object from the session object
    HINTERNET hConnection = NULL;
    hr = m_pOSMCtrl->CreateConnection(m_hSession, sServer, 80, hConnection);
    if (SUCCEEDED(hr))
    {
      //Iterate across the array of tiles to rerender
      for (INT_PTR i=0; i<m_Tiles.GetSize() && bSuccess; i++)
      {
        //Pull out the next tile to download
        const COSMCtrlMapOperationsDlgTile& tile = m_Tiles.ElementAt(i);

        //Form the name of the tile we will be rerendering
        CString sObject(MapnikTileProvider.GetDownloadObject(tile.m_nZoom, tile.m_nTileX, tile.m_nTileY) + _T("/dirty"));

        //Now issue the request to rerender
        COSMCtrlMapOperationsDlgEvent dlgEvent;
        dlgEvent.m_bSuccess = false;
        CStringA sResponse;
        hr = m_pOSMCtrl->DownloadPage(hConnection, sObject, TRUE, sResponse);
        if (FAILED(hr))
        {
          //report the error
          TRACE(_T("COSMCtrlMapOperationsDlg::ForceMapnikRerenderHelper, Failed to download page \"%s\", Error:%08X\n"), sObject.operator LPCTSTR(), hr);
          
          //Update the stats
          ++nTilesNotRerendered;
        }
        else
        {
          //Screen scrape the response to see if it worked
          if (sResponse.Find("Tile submitted for rendering") != -1)
          {
            //Update the stats
            ++nTilesRerendered;
            dlgEvent.m_bSuccess = true;
          }
          else
          {
            //Update the stats
            ++nTilesNotRerendered;
          }  
        }

        //Update the UI          
        dlgEvent.m_Event = COSMCtrlMapOperationsDlgEvent::SimpleStringStatus;
        dlgEvent.m_sString = sObject;
        dlgEvent.m_nItemData = i + 1;
        AddEvent(dlgEvent);

        //Check if we have been cancelled before we loop around
        bSuccess = (WaitForSingleObject(m_WorkerTerminateEvent, 0) == WAIT_TIMEOUT);
      }
      
      //Close the wininet connection
    #ifdef COSMCTRL_NOWINHTTP
      InternetCloseHandle(hConnection);
    #else
      WinHttpCloseHandle(hConnection);
    #endif
    }

    //Clean up the wininet session before we exit
  #ifdef COSMCTRL_NOWINHTTP
    InternetCloseHandle(m_hSession);
  #else
    WinHttpCloseHandle(m_hSession);
  #endif
    m_hSession = NULL;
  }

  //Finally add a event about how many items have been downloaded
  COSMCtrlMapOperationsDlgEvent dlgEvent;
  dlgEvent.m_Event = COSMCtrlMapOperationsDlgEvent::SimpleStringStatus;
  CString sTilesRerendered;
  sTilesRerendered.Format(_T("%d"), nTilesRerendered);
  CString sTilesNotRerendered;
  sTilesNotRerendered.Format(_T("%d"), nTilesNotRerendered);
  AfxFormatString2(dlgEvent.m_sString, IDS_OSMCTRL_RERENDER_TILES_STATS, sTilesRerendered, sTilesNotRerendered);
  AddEvent(dlgEvent);

  return TRUE;
}
Esempio n. 23
0
void CWebServer::OnRequest(CWebClientSocket* pClient, CStringA& hdr, CStringA& body)
{
    CPath p(pClient->m_path);
    CStringA ext = p.GetExtension().MakeLower();
    CStringA mime;
    if (ext.IsEmpty()) {
        mime = "text/html";
    } else {
        m_mimes.Lookup(ext, mime);
    }

    hdr = "HTTP/1.0 200 OK\r\n";

    bool fHandled = false, fCGI = false;

    if (!fHandled && m_webroot.IsDirectory()) {
        CStringA tmphdr;
        fHandled = fCGI = CallCGI(pClient, tmphdr, body, mime);

        if (fHandled) {
            tmphdr.Replace("\r\n", "\n");
            CAtlList<CStringA> hdrlines;
            ExplodeMin(tmphdr, hdrlines, '\n');
            POSITION pos = hdrlines.GetHeadPosition();
            while (pos) {
                POSITION cur = pos;
                CAtlList<CStringA> sl;
                CStringA key = Explode(hdrlines.GetNext(pos), sl, ':', 2);
                if (sl.GetCount() < 2) {
                    continue;
                }
                key.Trim().MakeLower();
                if (key == "content-type") {
                    mime = sl.GetTail().Trim();
                    hdrlines.RemoveAt(cur);
                } else if (key == "content-length") {
                    hdrlines.RemoveAt(cur);
                }
            }
            tmphdr = Implode(hdrlines, '\n');
            tmphdr.Replace("\n", "\r\n");
            hdr += tmphdr + "\r\n";
        }
    }

    RequestHandler rh = NULL;
    if (!fHandled && m_internalpages.Lookup(pClient->m_path, rh) && (pClient->*rh)(hdr, body, mime)) {
        if (mime.IsEmpty()) {
            mime = "text/html";
        }

        CString redir;
        if (pClient->m_get.Lookup(_T("redir"), redir)
                || pClient->m_post.Lookup(_T("redir"), redir)) {
            if (redir.IsEmpty()) {
                redir = '/';
            }

            hdr =
                "HTTP/1.0 302 Found\r\n"
                "Location: " + CStringA(redir) + "\r\n";
            return;
        }

        fHandled = true;
    }

    if (!fHandled && m_webroot.IsDirectory()) {
        fHandled = LoadPage(0, body, pClient->m_path);
    }

    UINT resid;
    CStringA res;
    if (!fHandled && m_downloads.Lookup(pClient->m_path, resid)
            && (LoadResource(resid, res, _T("FILE")) || LoadResource(resid, res, _T("PNG")))) {
        if (mime.IsEmpty()) {
            mime = "application/octet-stream";
        }
        memcpy(body.GetBufferSetLength(res.GetLength()), res.GetBuffer(), res.GetLength());
        fHandled = true;
    }

    if (!fHandled) {
        hdr = mime == "text/html"
              ? "HTTP/1.0 301 Moved Permanently\r\n" "Location: /404.html\r\n"
              : "HTTP/1.0 404 Not Found\r\n";
        return;
    }

    if ((mime == "text/html" || mime == "text/javascript") && !fCGI) {
        if (mime == "text/html") {
            hdr +=
                "Expires: Thu, 19 Nov 1981 08:52:00 GMT\r\n"
                "Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0\r\n"
                "Pragma: no-cache\r\n";

            CStringA debug;
            if (AfxGetAppSettings().fWebServerPrintDebugInfo) {
                debug += "<br><hr>\r\n";
                debug += "<div id=\"debug\">";
                CString key, value;
                POSITION pos;
                pos = pClient->m_hdrlines.GetStartPosition();
                while (pos) {
                    pClient->m_hdrlines.GetNextAssoc(pos, key, value);
                    debug += "HEADER[" + key + "] = " + value + "\r\n";
                }
                debug += "cmd: " + pClient->m_cmd + "\r\n";
                debug += "path: " + pClient->m_path + "\r\n";
                debug += "ver: " + pClient->m_ver + "\r\n";
                pos = pClient->m_get.GetStartPosition();
                while (pos) {
                    pClient->m_get.GetNextAssoc(pos, key, value);
                    debug += "GET[" + key + "] = " + value + "\r\n";
                }
                pos = pClient->m_post.GetStartPosition();
                while (pos) {
                    pClient->m_post.GetNextAssoc(pos, key, value);
                    debug += "POST[" + key + "] = " + value + "\r\n";
                }
                pos = pClient->m_cookie.GetStartPosition();
                while (pos) {
                    pClient->m_cookie.GetNextAssoc(pos, key, value);
                    debug += "COOKIE[" + key + "] = " + value + "\r\n";
                }
                pos = pClient->m_request.GetStartPosition();
                while (pos) {
                    pClient->m_request.GetNextAssoc(pos, key, value);
                    debug += "REQUEST[" + key + "] = " + value + "\r\n";
                }
                debug += "</div>";
            }
            body.Replace("[debug]", debug);
        }

        body.Replace("[browserpath]", "/browser.html");
        body.Replace("[commandpath]", "/command.html");
        body.Replace("[controlspath]", "/controls.html");
        body.Replace("[indexpath]", "/index.html");
        body.Replace("[path]", CStringA(pClient->m_path));
        body.Replace("[setposcommand]", CMD_SETPOS);
        body.Replace("[setvolumecommand]", CMD_SETVOLUME);
        body.Replace("[wmcname]", "wm_command");
        // TODO: add more general tags to replace
    }

    // gzip
    if (AfxGetAppSettings().fWebServerUseCompression && hdr.Find("Content-Encoding:") < 0)
        do {
            CString accept_encoding;
            pClient->m_hdrlines.Lookup(_T("accept-encoding"), accept_encoding);
            accept_encoding.MakeLower();
            CAtlList<CString> sl;
            ExplodeMin(accept_encoding, sl, ',');
            if (!sl.Find(_T("gzip"))) {
                break;
            }

            CHAR path[_MAX_PATH], fn[_MAX_PATH];
            if (!GetTempPathA(_MAX_PATH, path) || !GetTempFileNameA(path, "mpc_gz", 0, fn)) {
                break;
            }

            gzFile gf = gzopen(fn, "wb9");
            if (!gf || gzwrite(gf, (LPVOID)(LPCSTR)body, body.GetLength()) != body.GetLength()) {
                if (gf) {
                    gzclose(gf);
                }
                DeleteFileA(fn);
                break;
            }
            gzclose(gf);

            FILE* f = NULL;
            if (fopen_s(&f, fn, "rb")) {
                DeleteFileA(fn);
                break;
            }
            fseek(f, 0, 2);
            CHAR* s = body.GetBufferSetLength(ftell(f));
            fseek(f, 0, 0);
            int len = (int)fread(s, 1, body.GetLength(), f);
            ASSERT(len == body.GetLength());
#ifndef _DEBUG
            UNREFERENCED_PARAMETER(len);
#endif
            fclose(f);
            DeleteFileA(fn);

            hdr += "Content-Encoding: gzip\r\n";
        } while (0);

    CStringA content;
    content.Format(
        "Content-Type: %s\r\n"
        "Content-Length: %d\r\n",
        mime, body.GetLength());
    hdr += content;
}
Esempio n. 24
0
BOOL COSMCtrlMapOperationsDlg::ForceMapnikRerenderHelper()
{
  //Validate our parameters
  AFXASSUME(m_pOSMCtrl != NULL);

  //Next get the server to connect to
  COSMCtrlMapnikTileProvider MapnikTileProvider;
  CStringW sServer(MapnikTileProvider.GetDownloadServer());

  //Accumulate how many tiles we have request to rerender and which ones indicated a failure to rerender
  int nTilesRerendered = 0;
  int nTilesNotRerendered = 0;

  //Next create the WinHTTP session object
  CWinHTTPSession session;
  HRESULT hr = m_pOSMCtrl->CreateSession(session, 0);
  if (SUCCEEDED(hr))
  {
    //Now create the connection object from the session object
    CWinHTTPConnection connection;
    hr = connection.Initialize(session, sServer, MapnikTileProvider.GetDownloadPort());
    if (SUCCEEDED(hr))
    {
      //Iterate across the array of tiles to download
      BOOL bSuccess = TRUE;
      for (std::vector<COSMCtrlMapOperationsDlgTile>::size_type i=0; i<m_Tiles.size() && bSuccess; i++)
      {
        //Pull out the next tile to download
        const COSMCtrlMapOperationsDlgTile& tile = m_Tiles[i];

        //Now issue the request to rerender
        COSMCtrlMapOperationsDlgEvent dlgEvent;
        dlgEvent.m_bSuccess = false;
        LPCWSTR pwszAcceptTypes[2];
        pwszAcceptTypes[0] = L"*/*";
        pwszAcceptTypes[1] = NULL;
        CSyncWinHTTPDownloader winHttpRequest;
        //winHttpRequest.m_sFileToDownloadInto = sFile;
        CString sObject(MapnikTileProvider.GetDownloadObject(tile.m_nZoom, tile.m_nTileX, tile.m_nTileY) + _T("/dirty"));
        hr = winHttpRequest.Initialize(connection, CStringW(sObject), NULL, NULL, NULL, pwszAcceptTypes, WINHTTP_FLAG_REFRESH);
        if (FAILED(hr))
        {
          //report the error
          TRACE(_T("COSMCtrlMapOperationsDlg::ForceMapnikRerenderHelper, Failed to create request for object \"%s\", Error:%08X\n"), sObject.operator LPCTSTR(), hr);
            
          //Update the stats
          ++nTilesNotRerendered;
        }
        else
        {
          hr = winHttpRequest.SendRequestSync();
          if (FAILED(hr))
          {
            //report the error
            TRACE(_T("COSMCtrlMapOperationsDlg::ForceMapnikRerenderHelper, Failed to send request for object \"%s\", Error:%08X\n"), sObject.operator LPCTSTR(), hr);
            
            //Update the stats
            ++nTilesNotRerendered;
          }
          else
          {
            CStringA sResponse;
            sResponse.Append(reinterpret_cast<LPCSTR>(winHttpRequest.m_Response.GetData()), static_cast<int>(winHttpRequest.m_Response.GetSize()));
            if (sResponse.Find("Tile submitted for rendering") != -1)
            {
              //Update the stats
              ++nTilesRerendered;
              dlgEvent.m_bSuccess = true;
            }
            else
            {
              //Update the stats
              ++nTilesNotRerendered;
            }  
          }
        }

        //Update the UI          
        dlgEvent.m_Event = COSMCtrlMapOperationsDlgEvent::SimpleStringStatus;
        dlgEvent.m_sString = sObject;
        dlgEvent.m_nItemData = i + 1;
        AddEvent(dlgEvent);

        //Check if we have been cancelled before we loop around
        bSuccess = (WaitForSingleObject(m_WorkerTerminateEvent, 0) == WAIT_TIMEOUT);
      }
    }
  }

  //Finally add a event about how many items have been downloaded
  COSMCtrlMapOperationsDlgEvent dlgEvent;
  dlgEvent.m_Event = COSMCtrlMapOperationsDlgEvent::SimpleStringStatus;
  CString sTilesRerendered;
  sTilesRerendered.Format(_T("%d"), nTilesRerendered);
  CString sTilesNotRerendered;
  sTilesNotRerendered.Format(_T("%d"), nTilesNotRerendered);
  AfxFormatString2(dlgEvent.m_sString, IDS_OSMCTRL_RERENDER_TILES_STATS, sTilesRerendered, sTilesNotRerendered);
  AddEvent(dlgEvent);

  return TRUE;
}
Esempio n. 25
0
void CWebSocket::OnRequestReceived(char *pHeader, DWORD dwHeaderLen, char *pData, DWORD dwDataLen)
{
	EMULE_TRY

	CStringA	sHeader(pHeader, dwHeaderLen);
	CStringA	sURL;
	int			iIdx;
	bool		bFileReq = false;

	if (sHeader.Left(3) == "GET")
	{
		sURL = sHeader.TrimRight();
	}
	else if (sHeader.Left(4) == "POST")
	{
		CStringA		sData(pData, dwDataLen);

		sURL = '?';
		sURL += sData.Trim();	// '?' to imitate GET syntax for ParseURL
	}
	iIdx = sURL.Find(' ');
	if (iIdx >= 0)
		sURL = sURL.Mid(iIdx + 1);
	iIdx = sURL.Find(' ');
	if (iIdx >= 0)
		sURL = sURL.Left(iIdx);

	if (sURL.GetLength() > 4)
	{
		CStringA	strExt4 = sURL.Right(4).MakeLower();

		if (( (strExt4 == ".gif") || (strExt4 == ".jpg") || (strExt4 == ".png") ||
			(strExt4 == ".ico") || (strExt4 == ".css") || (sURL.Right(3).MakeLower() == ".js") ||
			(strExt4 == ".bmp") || (sURL.Right(5).MakeLower() == ".jpeg") || (strExt4 == ".xml") || (strExt4 == ".txt") )
			&& sURL.Find("..") < 0 )	// don't allow leaving the emule-webserver-folder for accessing files
		{
			bFileReq = true;
		}
	}

// HTTP header AcceptEncoding
	CStringA	strAcceptEncoding;
	iIdx = sHeader.Find("Accept-Encoding: ");
	if (iIdx >= 0)
	{
		int	iIdx2 = sHeader.Find("\r\n", iIdx += 17);

		strAcceptEncoding = sHeader.Mid(iIdx, iIdx2 - iIdx);
	}
// End AcceptEncoding

// HTTP header IfModifiedSince
	CStringA	strIfModifiedSince;
	iIdx = sHeader.Find("If-Modified-Since: ");
	if (iIdx >= 0)
	{
		int	iIdx2 = sHeader.Find("\r\n", iIdx += 19);

		strIfModifiedSince = sHeader.Mid(iIdx, iIdx2 - iIdx);
	}
// End IfModifiedSince

	ThreadData Data;

	Data.sURL = sURL;
	Data.pThis = m_pParent;
	Data.pSocket = this;
	Data.strAcceptEncoding = strAcceptEncoding;
	Data.strIfModifiedSince = strIfModifiedSince;

	if (!bFileReq)
		m_pParent->ProcessGeneralReq(Data);
	else
		m_pParent->ProcessFileReq(Data);

	Disconnect();

	EMULE_CATCH2
}
Esempio n. 26
0
CStringA	
FxInternal::TranscodePlugToHandle(const CStringA& plugStr)
{
	int iLastPos=0;
	int iThisPos=0;

	CStringA result;
	CStringA partial;


	int rootIdx= plugStr.Find(DirectXShader::RootLongName.asChar());
	if(rootIdx != 0)
		return CStringA();

	if( plugStr[(int)DirectXShader::RootLongName.length()] != '.' )
		return CStringA();

	
	CStringA rootlessPlugStr= plugStr.Mid(DirectXShader::RootLongName.length()+1);

	CStringA subStr;
	while( iLastPos= iThisPos, 
		subStr=rootlessPlugStr.Tokenize(".[]", iThisPos), 
		iThisPos != -1 )
	{
		if(iLastPos == 0)
		{

			partial= subStr;

			int prefixIdx= subStr.Find(DirectXShader::RootShortName.asChar());
			if(prefixIdx != 0)
				return CStringA();

			result= subStr.Mid(DirectXShader::RootShortName.length());
		}
		else if(rootlessPlugStr[iLastPos-1]=='.'
			|| (rootlessPlugStr[iLastPos-1]==']' && rootlessPlugStr[iLastPos]=='.'))
		{
			DXCC_ASSERT(subStr.Find(partial) == 0);

			CStringA uniquePart= subStr.Mid( partial.GetLength() );

			partial= subStr;

			result.AppendFormat(".%s", uniquePart);
		}
		else if(rootlessPlugStr[iLastPos-1]=='[' && rootlessPlugStr[iThisPos-1]==']')
		{
			result.AppendFormat("[%s]", subStr);
		}
		else
			DXCC_ASSERT(false);
	}


	//remove last array 
	if( result[result.GetLength()-1] == ']' )
	{
		int lastArrayAccess= result.ReverseFind('[');
		DXCC_ASSERT(lastArrayAccess != -1);

		result= result.Left(lastArrayAccess);
	}

	int lastMember= result.ReverseFind('.');
	if(lastMember == -1)
		return CStringA();

	if(result.Mid(lastMember+1) != "Value")
		return CStringA();

	result= result.Left(lastMember);
	return result;
}