Esempio n. 1
0
void CCookie::ParseFieldKV(const CStringA& strField, CStringA& strKey, CStringA& strVal, char chSep)
{
	int i = strField.Find(chSep);

	if(i < 0)
		strKey = strField;
	else
	{
		strKey = strField.Left(i);
		strVal = strField.Mid(i + 1);

		strVal.Trim();
	}

	strKey.Trim();
}
Esempio n. 2
0
bool CIPFilter::ParseFilterLine2(const CStringA& sbuffer, uint32& ip1, uint32& ip2, UINT& level, CStringA& desc) const
{
	int iPos = sbuffer.ReverseFind(':');
	if (iPos < 0)
		return false;

	desc = sbuffer.Left(iPos);
	desc.Replace("PGIPDB", "");
	desc.Trim();

	CStringA strIPRange = sbuffer.Mid(iPos + 1, sbuffer.GetLength() - iPos);
	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)
		return false;

	((BYTE*)&ip1)[0] = (BYTE)u4;
	((BYTE*)&ip1)[1] = (BYTE)u3;
	((BYTE*)&ip1)[2] = (BYTE)u2;
	((BYTE*)&ip1)[3] = (BYTE)u1;

	((BYTE*)&ip2)[0] = (BYTE)u8;
	((BYTE*)&ip2)[1] = (BYTE)u7;
	((BYTE*)&ip2)[2] = (BYTE)u6;
	((BYTE*)&ip2)[3] = (BYTE)u5;

	level = DFLT_FILTER_LEVEL;

	return true;
}
Esempio n. 3
0
CStringA netbios_name::GetANSIName() const
{
	CStringA sName;
	LPSTR szName = sName.GetBuffer( NCBNAMSZ );
	CopyMemory( szName, (LPCSTR)netbiosed.name, NCBNAMSZ - 1 );
	szName[ NCBNAMSZ - 1 ] = 0;
	sName.ReleaseBuffer();
	sName.Trim();
	sName.OemToAnsi();
	return sName;
}
Esempio n. 4
0
BOOL LoadIDs(LPCTSTR szFilename)
{
	BOOL bSuccess = FALSE;

	FILE* pFile = NULL;
	if ( _tfopen_s( &pFile, szFilename, _T("rb") ) == 0 )
	{
		for (;;)
		{
			CStringA sLine;
			CHAR* res = fgets( sLine.GetBuffer( 4096 ), 4096, pFile );
			sLine.ReleaseBuffer();
			if ( ! res )
				break;		// End of file
			sLine.Trim( " \t\r\n" );
			if ( sLine.IsEmpty() || sLine.GetAt( 0 ) != '#' )
				continue;		// Skip empty lines
			int nPos = sLine.FindOneOf( " \t" );
			if ( nPos == -1 || sLine.Left( nPos ) != "#define" )
				continue;		// Skip unknown line
			sLine = sLine.Mid( nPos + 1 ).TrimLeft( " \t" );
			nPos = sLine.FindOneOf( " \t" );
			if ( nPos == -1 )
				continue;		// Skip unknown line
			CStringA sID = sLine.Left( nPos );
			sLine = sLine.Mid( nPos + 1 ).TrimLeft( " \t" );
			UINT nID = 0;
			if ( sLine.Left( 2 ).CompareNoCase( "0x" ) == 0 )
			{
				if ( sscanf_s( sLine, "%x", &nID ) != 1 )
					continue;	// Skip unknown line
			}
			else
			{
				if ( sscanf_s( sLine, "%u", &nID ) != 1 )
					continue;	// Skip unknown line
			}
			if ( g_oIDs.Lookup( sID, nID ) )
			{
				_tprintf( _T("Error: Duplicate ID %hs\n"), sID );
				continue;
			}
			g_oIDs.SetAt( sID, nID );
			bSuccess = TRUE;
		}
		fclose( pFile );
	}

	return bSuccess;
}
void SplitSysListContent(const CStringA& strContent)
{
	USES_CONVERSION;

	int curPos = 0;
	CStringA resToken = strContent.Tokenize("\r\n", curPos);
	while (resToken != "")
	{
		resToken.Trim();

		if (!resToken.IsEmpty() && resToken.GetAt(0) != '#')
		{
			int nPoundKey = resToken.Find('#');
			if (nPoundKey != -1)
				resToken = resToken.Mid(0, nPoundKey);

			resToken.Replace('/', '\\');

			// (1) 注册表
			if (resToken.GetAt(0) == '$')
			{
				if (resToken.GetLength() > 3)
				{
					if (resToken.GetAt(1) == '{')
						DoRegistryPath(resToken);
					else if (resToken.GetAt(1) == '[')
						DoRegistryFile(resToken);
				}
			}
			// (2) 单独文件
			else if (resToken.GetAt(0) == '@')
				DoOnlyFileName(resToken.Mid(1));

			// (3) 其他
			else
				DoFilePathName(resToken);
		}

		resToken = strContent.Tokenize("\r\n", curPos);
	}
}
Esempio n. 6
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. 7
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. 8
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. 9
0
bool IgnoreCommand::Execute()
{
	bool bmask=false;

	if(parser.HasKey(_T("onlymask")))
	{
		bmask=true;
	}

	bool ret = CAppUtils::IgnoreFile(pathList,bmask);

	if (parser.HasKey(_T("delete")))
	{
		int key;

		CString format;

		if(CMessageBox::Show(hwndExplorer, _T("Keep file locally?"), _T("TortoiseGit"), MB_ICONERROR|MB_YESNO) == IDYES)
		{
			format= _T("git.exe update-index --force-remove -- \"%s\"");
		}
		else
		{
			format=_T("git.exe rm -r -f -- \"%s\"");
		}

		CString output;
		CString cmd;
		int nPath;
		for(nPath = 0; nPath < pathList.GetCount(); nPath++)
		{

			cmd.Format(format,pathList[nPath].GetGitPathString());
			if(g_Git.Run(cmd,&output,CP_ACP))
			{
				key=CMessageBox::Show(hwndExplorer, output, _T("TortoiseGit"), MB_ICONERROR|MB_OKCANCEL);
				if(key == IDCANCEL)
					return FALSE;

			}
		}

		output.Format(_T("%d files removed"),nPath);

		CShellUpdater::Instance().AddPathsForUpdate(pathList);

		CMessageBox::Show(hwndExplorer, output, _T("TortoiseGit"), MB_ICONINFORMATION|MB_OK);
	}

	CShellUpdater::Instance().AddPathsForUpdate(orgPathList);
	CShellUpdater::Instance().Flush();

	return ret;
#if 0
	CString filelist;
	BOOL err = FALSE;
	for(int nPath = 0; nPath < pathList.GetCount(); nPath++)
	{
		CString name = CPathUtils::PathPatternEscape(pathList[nPath].GetFileOrDirectoryName());
		if (parser.HasKey(_T("onlymask")))
		{
			name = _T("*")+pathList[nPath].GetFileExtension();
		}
		filelist += name + _T("\n");
		CTSVNPath parentfolder = pathList[nPath].GetContainingDirectory();
		SVNProperties props(parentfolder, SVNRev::REV_WC, false);
		CStringA value;
		for (int i=0; i<props.GetCount(); i++)
		{
			CString propname(props.GetItemName(i).c_str());
			if (propname.CompareNoCase(_T("svn:ignore"))==0)
			{
				//treat values as normal text even if they're not
				value = (char *)props.GetItemValue(i).c_str();
			}
		}
		if (value.IsEmpty())
			value = name;
		else
		{
			// make sure we don't have duplicate entries
			std::set<CStringA> ignoreItems;
			ignoreItems.insert(CUnicodeUtils::GetUTF8(name));
			CStringA token;
			int curPos = 0;
			token= value.Tokenize("\n",curPos);
			while (token != _T(""))
			{
				token.Trim();
				ignoreItems.insert(token);
				token = value.Tokenize("\n", curPos);
			};
			value.Empty();
			for (std::set<CStringA>::iterator it = ignoreItems.begin(); it != ignoreItems.end(); ++it)
			{
				value += *it;
				value += "\n";
			}
		}
		if (!props.Add(_T("svn:ignore"), (LPCSTR)value))
		{
			CString temp;
			temp.Format(IDS_ERR_FAILEDIGNOREPROPERTY, (LPCTSTR)name);
			temp += _T("\n");
			temp += props.GetLastErrorMsg().c_str();
			CMessageBox::Show(hwndExplorer, temp, _T("TortoiseGit"), MB_ICONERROR);
			err = TRUE;
			break;
		}
	}
	if (err == FALSE)
	{
		CString temp;
		temp.Format(IDS_PROC_IGNORESUCCESS, (LPCTSTR)filelist);
		CMessageBox::Show(hwndExplorer, temp, _T("TortoiseGit"), MB_ICONINFORMATION);
		return true;
	}
#endif
}
Esempio n. 10
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. 11
0
CCookie* CCookie::FromString(const CStringA& strCookie, LPCSTR lpszDefaultDomain, LPCSTR lpszDefaultPath)
{
	CStringA strName;
	CStringA strValue;
	CStringA strDomain;
	CStringA strPath;

	int iMaxAge			  = -1;
	BOOL bHttpOnly		  = FALSE;
	BOOL bSecure		  = FALSE;
	EnSameSite enSameSite = SS_NONE;

	int i		= 0;
	int iStart	= 0;

	while(TRUE)
	{
		CStringA strField = strCookie.Tokenize(COOKIE_FIELD_SEP, iStart);
		strField.Trim();

		if(strField.IsEmpty())
			break;

		if(i == 0)
		{
			ParseFieldKV(strField, strName, strValue, COOKIE_KV_SEP_CHAR);

			if(strName.IsEmpty())
				return nullptr;
		}
		else
		{
			CStringA strKey;
			CStringA strVal;

			ParseFieldKV(strField, strKey, strVal, COOKIE_KV_SEP_CHAR);

			if(strKey.CompareNoCase(COOKIE_DOMAIN) == 0)
				strDomain = strVal;
			else if(strKey.CompareNoCase(COOKIE_PATH) == 0)
				strPath = strVal;
			else if(strKey.CompareNoCase(COOKIE_MAX_AGE) == 0 && !strVal.IsEmpty())
				iMaxAge = atoi(strVal);
			else if(strKey.CompareNoCase(COOKIE_EXPIRES) == 0 && !strVal.IsEmpty() && iMaxAge == -1)
			{
				__time64_t tmExpires = -1;

				if(!ParseExpires(strVal, tmExpires))
					return nullptr;

				iMaxAge = ExpiresToMaxAge(tmExpires);
			}
			else if(strKey.CompareNoCase(COOKIE_HTTPONLY) == 0)
				bHttpOnly = TRUE;
			else if(strKey.CompareNoCase(COOKIE_SECURE) == 0)
				bSecure = TRUE;
			else if(strKey.CompareNoCase(COOKIE_SAMESITE) == 0)
			{
				if(strVal.IsEmpty() || strVal.CompareNoCase(COOKIE_SAMESITE_STRICT) == 0)
					enSameSite = SS_STRICT;
				else if(strVal.CompareNoCase(COOKIE_SAMESITE_LAX) == 0)
					enSameSite = SS_LAX;
			}
		}

		++i;
	}

	if(!AdjustDomain(strDomain, lpszDefaultDomain) || !AdjustPath(strPath, lpszDefaultPath))
		return nullptr;

	CCookie* pCookie = new CCookie(strName, strValue, strDomain, strPath, iMaxAge, bHttpOnly, bSecure, enSameSite);
	ASSERT(pCookie->IsValid());

	return pCookie;
}
Esempio n. 12
0
bool CSubtitleDlDlg::Parse()
{
    // Parse raw list
    ISDb::movie m;
    ISDb::subtitle sub;

    CAtlList<CStringA> sl;
    Explode(m_pTA->raw_list, sl, '\n');
    CString str;

    POSITION pos = sl.GetHeadPosition();
    while (pos) {
        str = sl.GetNext(pos);

        CStringA param = str.Left(max(0, str.Find('=')));
        CStringA value = str.Mid(str.Find('=') + 1);

        if (param == "ticket") {
            m_pTA->ticket = value;
        } else if (param == "movie") {
            m.reset();
            Explode(value.Trim(" |"), m.titles, '|');
        } else if (param == "subtitle") {
            sub.reset();
            sub.id = atoi(value);
        } else if (param == "name") {
            sub.name = value;
        } else if (param == "discs") {
            sub.discs = atoi(value);
        } else if (param == "disc_no") {
            sub.disc_no = atoi(value);
        } else if (param == "format") {
            sub.format = value;
        } else if (param == "iso639_2") {
            sub.iso639_2 = value;
        } else if (param == "language") {
            sub.language = value;
        } else if (param == "nick") {
            sub.nick = value;
        } else if (param == "email") {
            sub.email = value;
        } else if (param.IsEmpty() && value == "endsubtitle") {
            m.subs.AddTail(sub);
        } else if (param.IsEmpty() && value == "endmovie") {
            m_pTA->raw_movies.AddTail(m);
        } else if (param.IsEmpty() && value == "end") {
            break;
        }
    }

    // Parse movies
    pos = m_pTA->raw_movies.GetHeadPosition();
    while (pos) {
        ISDb::movie& raw_movie = m_pTA->raw_movies.GetNext(pos);
        isdb_movie_parsed p;

        CStringA titlesA = Implode(raw_movie.titles, '|');
        titlesA.Replace("|", ", ");
        p.titles = UTF8To16(titlesA);
        p.checked = false;

        POSITION pos2 = raw_movie.subs.GetHeadPosition();
        while (pos2) {
            const ISDb::subtitle& s = raw_movie.subs.GetNext(pos2);
            p.name = UTF8To16(s.name);
            p.language = s.language;
            p.format = s.format;
            p.disc.Format(_T("%d/%d"), s.disc_no, s.discs);
            p.ptr = reinterpret_cast<DWORD_PTR>(&s);

            m_parsed_movies.Add(p);
        }
    }

    bool ret = true;
    if (m_parsed_movies.IsEmpty()) {
        ret = false;
    }

    return ret;
}
Esempio n. 13
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. 14
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;
}
void CFtpClientReqSocket::DataReceived(const BYTE* pucData, UINT uSize)
{	
	if( !IsEntireResponse((const char*)pucData,uSize) ) //先检查是否有一个完整HeaderLine回来了..
		return ;

	CStringA strLine;
	CStringA strNumber;
	CStringA strMultiNumber;
	CStringA strMultiReply;

	LPCSTR pData=(LPCSTR)pucData;
	bool bMultiLine = false;

	while ( uSize>0 )
	{
		LPCSTR pszNl = (LPCSTR)memchr(pData, '\n', uSize);

		if(!pszNl)
			return;
		
		int iLineLen = pszNl - pData;
		ASSERT( iLineLen >= 0 );
		if (iLineLen > 0)
			strLine = CStringA(pData, iLineLen - 1); 

		pData += (strLine.GetLength() + 2);
		uSize -= (strLine.GetLength() + 2);

		if( GetClient() )
		{
			GetClient()->AddPeerLog(new CTraceServerMessage(CString(strLine)));
		}

		BOOL bNumber = ( strLine.GetLength() >= 3 ) &&
			_istdigit( strLine[0] ) && _istdigit( strLine[1] ) && _istdigit( strLine[2] );

		if ( bNumber )
			strNumber = strLine.Left( 3 );

		if ( !bMultiLine && bNumber && strLine[3] == _T('-') )
		{
			// Got first line of multi-line reply
			bMultiLine = TRUE;
			strMultiNumber = strNumber;
			strMultiReply = strLine.Mid( 4 );
		}
		else if ( !bMultiLine && bNumber )
		{
			// Got single-line reply
			if ( !OnHeaderLine( strNumber, strLine.Mid( 4 ).Trim( " \t\r\n" ) ) ) 
				return ;
		}
		else if ( bMultiLine && bNumber && strLine[3] == ' ' &&
			strMultiNumber == strNumber )
		{
			// Got last line of multi-line reply
			bMultiLine = FALSE;
			strMultiReply += "\n";
			strMultiReply += strLine.Mid( 4 );
			if ( ! OnHeaderLine( strNumber, strMultiReply.Trim( " \t\r\n" ) ) )
				return ;
		}
		else if ( bMultiLine )
		{			
			strMultiReply += "\n";
			strMultiReply += strLine;
		}
	}
}
Esempio n. 16
0
bool UnIgnoreCommand::Execute()
{
	CString filelist;
	BOOL err = FALSE;
	for (int nPath = 0; nPath < pathList.GetCount(); ++nPath)
	{
		CString name = CPathUtils::PathPatternEscape(pathList[nPath].GetFileOrDirectoryName());
		if (parser.HasKey(L"onlymask"))
			name = L'*' + pathList[nPath].GetFileExtension();
		filelist += name + L'\n';
		CTSVNPath parentfolder = pathList[nPath].GetContainingDirectory();
		SVNProperties props(parentfolder, SVNRev::REV_WC, false);
		CStringA value;
		for (int i = 0; i < props.GetCount(); ++i)
		{
			CString propname(props.GetItemName(i).c_str());
			if (propname.CompareNoCase(L"svn:ignore") == 0)
			{
				//treat values as normal text even if they're not
				value = (char *)props.GetItemValue(i).c_str();
				break;
			}
		}
		value = value.Trim("\n\r");
		value += '\n';
		value.Remove('\r');
		value.Replace("\n\n", "\n");

		// Delete all occurrences of 'name'
		// "\n" is temporarily prepended to make the algorithm easier
		value = "\n" + value;
		value.Replace("\n" + CUnicodeUtils::GetUTF8(name) + "\n", "\n");
		value = value.Mid(1);

		CStringA sTrimmedvalue = value;
		sTrimmedvalue.Trim();
		if (sTrimmedvalue.IsEmpty())
		{
			if (!props.Remove(L"svn:ignore"))
			{
				CString temp;
				temp.Format(IDS_ERR_FAILEDUNIGNOREPROPERTY, (LPCTSTR)name);
				CMessageBox::Show(hwndExplorer, temp, L"TortoiseGit", MB_ICONERROR);
				err = TRUE;
				break;
			}
		}
		else
		{
			if (!props.Add(L"svn:ignore", (LPCSTR)value))
			{
				CString temp;
				temp.Format(IDS_ERR_FAILEDUNIGNOREPROPERTY, (LPCTSTR)name);
				CMessageBox::Show(hwndExplorer, temp, L"TortoiseGit", MB_ICONERROR);
				err = TRUE;
				break;
			}
		}
	}
	if (err == FALSE)
	{
		CString temp;
		temp.Format(IDS_PROC_UNIGNORESUCCESS, (LPCTSTR)filelist);
		CMessageBox::Show(hwndExplorer, temp, L"TortoiseGit", MB_ICONINFORMATION);
		return true;
	}
	return false;
}
Esempio n. 17
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. 18
0
// ==> IP Filter White List [Stulle] - Stulle
void CIPFilter::AddFromFileWhite(LPCTSTR pszFilePath)
{
	FILE* readFile = _tfsopen(pszFilePath, _T("r"), _SH_DENYWR);
	if (readFile != NULL)
	{
		_setmode(fileno(readFile), _O_TEXT);

		int iLine = 0;
		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 (white): ignored line %u\n", iLine) : 0 );
				continue;
			}

			bool bValid = false;
			uint32 start = 0;
			uint32 end = 0;
			UINT level = 0;
			CStringA desc;
			bValid = ParseFilterLine1(sbuffer, start, end, level, desc);

			// add a filter
			if (bValid)
			{
				AddIPRangeWhite(start, end, level, desc);
				DEBUG_ONLY( TRACE("Added White Entry - start: %u end: %u level: %u desc: %s\n", start, end, level, desc));
			}
			else
			{
				sbuffer.Trim(" \t\r\n");
				DEBUG_ONLY( (!sbuffer.IsEmpty()) ? TRACE("IP filter (white list): ignored line %u\n", iLine) : 0 );
			}
		}
		fclose(readFile);

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

		// merge overlapping and adjacent filter ranges
		if (m_iplist_White.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_White.GetCount()];
			memset(pcToDelete, 0, m_iplist_White.GetCount());
			int iNumToDelete = 0;

			SIPFilter* pPrv = m_iplist_White[0];
			int i = 1;
			while (i < m_iplist_White.GetCount())
			{
				SIPFilter* pCur = m_iplist_White[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...
					}
					else
					{
						// if we have identical entries, use the lowest 'level'
						if (pCur->level < pPrv->level)
							pPrv->level = pCur->level;
					}
					delete pCur;
					//m_iplist_White.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_White.GetCount() - iNumToDelete);
				int iNewListIndex = 0;
				for (int i = 0; i < m_iplist_White.GetCount(); i++) {
					if (!pcToDelete[i])
						newList[iNewListIndex++] = m_iplist_White[i];
				}
				ASSERT( iNewListIndex == newList.GetSize() );

				// Replace current list with new list. Dump, but still fast enough (only 1 memcpy)
				m_iplist_White.RemoveAll();
				m_iplist_White.Append(newList);
				newList.RemoveAll();
				m_bModified = true;
			}
			delete[] pcToDelete;
		}
	}
	if(m_iplist_White.GetCount()>0)
		AddLogLine(false, GetResString(IDS_IPFILTERWHITELOADED), m_iplist_White.GetCount());
	return;
}
Esempio n. 19
0
static int Launch()
{
  Log(L"Launching browser...");

  DWORD processID;

  // The interface that allows us to activate the browser
  CComPtr<IApplicationActivationManager> activateMgr;
  if (FAILED(CoCreateInstance(CLSID_ApplicationActivationManager, nullptr,
                              CLSCTX_LOCAL_SERVER,
                              IID_IApplicationActivationManager,
                              (void**)&activateMgr))) {
    Fail(false, L"CoCreateInstance CLSID_ApplicationActivationManager failed.");
    return FAILURE;
  }
  
  HRESULT hr;
  WCHAR appModelID[256];
  // Activation is based on the browser's registered app model id
  if (!GetDefaultBrowserAppModelID(appModelID, (sizeof(appModelID)/sizeof(WCHAR)))) {
    Fail(false, L"GetDefaultBrowserAppModelID failed.");
    return FAILURE;
  }
  Log(L"App model id='%s'", appModelID);

  // Hand off focus rights if the terminal has focus to the out-of-process
  // activation server (explorer.exe). Without this the metro interface
  // won't launch.
  hr = CoAllowSetForegroundWindow(activateMgr, nullptr);
  if (FAILED(hr)) {
    // Log but don't fail. This has happened on vms with certain terminals run by
    // QA during mozmill testing.
    Log(L"Windows focus rights hand off failed (HRESULT=0x%X). Ignoring.", hr);
  }

  Log(L"Harness process id: %d", GetCurrentProcessId());

  // If provided, validate the firefox path passed in.
  int binLen = wcslen(kFirefoxExe);
  if (sFirefoxPath.GetLength() && sFirefoxPath.Right(binLen) != kFirefoxExe) {
    Log(L"firefoxpath is missing a valid bin name! Assuming '%s'.", kFirefoxExe);
    if (sFirefoxPath.Right(1) != L"\\") {
      sFirefoxPath += L"\\";
    }
    sFirefoxPath += kFirefoxExe;
  }

  // Because we can't pass command line args, we store params in a
  // tests.ini file in dist/bin which the browser picks up on launch.
  CStringA testFilePath;
  if (sFirefoxPath.GetLength()) {
    // Use the firefoxpath passed to us by the test harness
    int index = sFirefoxPath.ReverseFind('\\');
    if (index == -1) {
      Fail(false, L"Bad firefoxpath path");
      return FAILURE;
    }
    testFilePath = sFirefoxPath.Mid(0, index);
    testFilePath += "\\";
    testFilePath += kMetroTestFile;
  } else {
    // Use the module path
    char path[MAX_PATH];
    if (!GetModuleFileNameA(nullptr, path, MAX_PATH)) {
      Fail(false, L"GetModuleFileNameA errorno=%d", GetLastError());
      return FAILURE;
    }
    char* slash = strrchr(path, '\\');
    if (!slash)
      return FAILURE;
    *slash = '\0'; // no trailing slash
    testFilePath = path;
    testFilePath += "\\";
    sFirefoxPath = testFilePath;
    sFirefoxPath += kFirefoxExe;
    testFilePath += kMetroTestFile;
  }

  // Make sure the firefox bin exists
  if (GetFileAttributesW(sFirefoxPath) == INVALID_FILE_ATTRIBUTES) {
    Fail(false, L"Invalid bin path: '%s'", sFirefoxPath);
    return FAILURE;
  }

  Log(L"Using bin path: '%s'", sFirefoxPath);

  Log(L"Writing out tests.ini to: '%s'", CStringW(testFilePath));
  HANDLE hTestFile = CreateFileA(testFilePath, GENERIC_WRITE,
                                 0, nullptr, CREATE_ALWAYS,
                                 FILE_ATTRIBUTE_NORMAL,
                                 nullptr);
  if (hTestFile == INVALID_HANDLE_VALUE) {
    Fail(false, L"CreateFileA errorno=%d", GetLastError());
    return FAILURE;
  }

  DeleteTestFileHelper dtf(testFilePath);

  // nsAppRunner expects the first param to be the bin path, just like a
  // normal startup. So prepend our bin path to our param string we write.
  CStringA asciiParams = sFirefoxPath;
  asciiParams += " ";
  asciiParams += sAppParams;
  asciiParams.Trim();
  Log(L"Browser command line args: '%s'", CString(asciiParams));
  if (!WriteFile(hTestFile, asciiParams, asciiParams.GetLength(),
                 nullptr, 0)) {
    CloseHandle(hTestFile);
    Fail(false, L"WriteFile errorno=%d", GetLastError());
    return FAILURE;
  }
  FlushFileBuffers(hTestFile);
  CloseHandle(hTestFile);

  // Create a named stdout pipe for the browser
  if (!SetupTestOutputPipe()) {
    Fail(false, L"SetupTestOutputPipe failed (errno=%d)", GetLastError());
    return FAILURE;
  }

  // Launch firefox
  hr = activateMgr->ActivateApplication(appModelID, L"", AO_NOERRORUI, &processID);
  if (FAILED(hr)) {
    Fail(true, L"ActivateApplication result %X", hr);
    return RETRY;
  }

  Log(L"Activation succeeded.");

  // automation.py picks up on this, don't mess with it.
  Log(L"METRO_BROWSER_PROCESS=%d", processID);

  HANDLE child = OpenProcess(SYNCHRONIZE, FALSE, processID);
  if (!child) {
    Fail(false, L"Couldn't find child process. (%d)", GetLastError());
    return FAILURE;
  }

  Log(L"Waiting on child process...");

  MSG msg;
  DWORD waitResult = WAIT_TIMEOUT;
  HANDLE handles[2] = { child, gTestOutputPipe };
  while ((waitResult = MsgWaitForMultipleObjects(2, handles, FALSE, INFINITE, QS_ALLINPUT)) != WAIT_OBJECT_0) {
    if (waitResult == WAIT_FAILED) {
      Log(L"Wait failed (errno=%d)", GetLastError());
      break;
    } else if (waitResult == WAIT_OBJECT_0 + 1) {
      ReadPipe();
    } else if (waitResult == WAIT_OBJECT_0 + 2 &&
               PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE)) {
      TranslateMessage(&msg);
      DispatchMessage(&msg);
    }
  }

  ReadPipe();
  CloseHandle(gTestOutputPipe);
  CloseHandle(child);

  Log(L"Exiting.");
  return SUCCESS;
}