Esempio n. 1
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
			ret2.AppendFormat("%%%02X", (unsigned char)c);
	}
	CStringA ret;
	for (i=0; ret2[i]; ++i)
	{
		c = (unsigned char)ret2[i];
		if (uri_autoescape_chars[c])
		{
			// no escaping needed for that char
			ret += (unsigned char)ret2[i];
		}
		else // char needs escaping
			ret.AppendFormat("%%%02X", (unsigned char)c);
	}

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

	return ret;
}
Esempio n. 2
0
CStringA HtmlSpecialChars(CStringA str, bool bQuotes /*= false*/)
{
    str.Replace("&", "&amp;");
    str.Replace("\"", "&quot;");
    if (bQuotes) {
        str.Replace("\'", "&#039;");
    }
    str.Replace("<", "&lt;");
    str.Replace(">", "&gt;");

    return str;
}
Esempio n. 3
0
void CFileMgrDB::RemoveFile(CFileTaskItem * item, CONST BYTE * lpHash)
{
	CStringA strCmd, strCmd2;
	if(lpHash != NULL && !isnulmd4(lpHash))
	{
		CHAR strHash[33];
		md4strA(lpHash, strHash);
		strCmd.Format("SELECT id FROM files WHERE hash='%s'", strHash);
		strCmd2.Format("DELETE FROM files WHERE hash='%s'", strHash);
	}
	else
	{
		CStringA strUrl = StrToUtf8(item->m_strUrl);
		strUrl.Replace("'", "''");
		strCmd.Format("SELECT id FROM files WHERE url='%s'", strUrl);
		strCmd2.Format("DELETE FROM files WHERE url='%s'", strUrl);
	}

	if(!m_db->Prepare(strCmd))
		return;
	if(!m_db->Step())
	{
		m_db->Finalize();
		return;
	}
	UINT id = m_db->GetColInt(0);

	strCmd.Format("DELETE FROM urls WHERE fid=%d", id);
	SQL_EXEC(strCmd);
	SQL_EXEC(strCmd2);
}
Esempio n. 4
0
void CFileMgrDB::UpdateFiles(CRBMap<FILEKEY,CFileTaskItem*> & FileList)
{
	CStringA strCmd, strCmd2;
	CHAR strHash[33];

	m_db->Exec("begin transaction");
	POSITION pos = FileList.GetHeadPosition();
	while (pos)
	{		
		FILEKEY fk = FileList.GetKeyAt(pos);
		CFileTaskItem *item = FileList.GetNextValue(pos);
		md4strA(fk.key, strHash);

		CStringA strPath = StrToUtf8(item->m_strFilePath), strUrl = StrToUtf8(item->m_strUrl), strName = StrToUtf8(item->m_FileName), strLink = StrToUtf8(item->m_strEd2kLink);
		strPath.Replace("'", "''");
		strUrl.Replace("'", "''");
		strName.Replace("'", "''");
		strLink.Replace("'", "''");
	
		strCmd2.Format("INSERT INTO files (hash, state, path, url, size, name, ed2klink, filetime, metbakid) "
			"VALUES ('%s',%u,'%s','%s',%I64u,'%s','%s',%I64u,%u)", strHash, item->m_nFileState, strPath, strUrl, item->m_FileSize, strName,
			strLink, item->m_tFiletime.GetTime(), item->m_metBakId);
		SQL_EXEC(strCmd2);
	}   
	m_db->Exec("end transaction");	
}
extern "C" void __declspec(dllexport) detect_httpd(
  HWND hwndParent, 
  int string_size, 
	char *variables, 
  stack_t **stacktop)
{
	EXDLL_INIT();

	TCHAR str[1024];
	ULONG len = 1024;
	char szPath[1024]="";
	bool bDetected = false;

	CRegKey regKey;
	if(ERROR_SUCCESS==regKey.Open(HKEY_LOCAL_MACHINE, _T("SYSTEM\\CurrentControlSet\\services\\Apache2.2")))
	{
		if(ERROR_SUCCESS==regKey.QueryStringValue(_T("ImagePath"), str, &len))
		{
			bDetected = true;
		}
	}

	CStringA sPath = str;
	int nPos = sPath.Find("\\bin\\httpd.exe");
	if(nPos<0)
		bDetected = false;
	sPath = sPath.Mid(0, nPos);
	sPath.Replace("\"", "");
		
	if(bDetected)
		pushstring(sPath.GetBuffer());	
	else
		pushstring("");	
}
Esempio n. 6
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;
}
void CEditPropMergeLogTemplate::OnOK()
{
    TProperties newProps;
    PropValue pVal;

    CString sText;
    GetDlgItemText(IDC_TITLE, sText);
    CStringA propVal = CUnicodeUtils::GetUTF8(sText);
    propVal.Replace("\r\n", "\n");
    pVal.value = propVal;
    pVal.remove = (pVal.value.empty());
    newProps[PROJECTPROPNAME_MERGELOGTEMPLATETITLE] = pVal;

    GetDlgItemText(IDC_TITLEREVERSE, sText);
    propVal = CUnicodeUtils::GetUTF8(sText);
    propVal.Replace("\r\n", "\n");
    pVal.value = propVal;
    pVal.remove = (pVal.value.empty());
    newProps[PROJECTPROPNAME_MERGELOGTEMPLATEREVERSETITLE] = pVal;

    GetDlgItemText(IDC_MSG, sText);
    propVal = CUnicodeUtils::GetUTF8(sText);
    propVal.Replace("\r\n", "\n");
    pVal.value = propVal;
    pVal.remove = (pVal.value.empty());
    newProps[PROJECTPROPNAME_MERGELOGTEMPLATEMSG] = pVal;

    pVal.value = IsDlgButtonChecked(IDC_TITLEBOTTOM) ? "yes" : "";
    pVal.remove = (pVal.value.empty());
    newProps[PROJECTPROPNAME_MERGELOGTEMPLATETITLEBOTTOM] = pVal;

    m_bChanged = true;
    m_properties = newProps;

    __super::OnOK();
}
Esempio n. 8
0
///
///	@brief	네이버 메일 ssl 통신 시에 본문 로그를 남김
///
BOOL WINAPI InternetWriteFileCallback(
  _In_  HINTERNET hFile,
  _In_  LPCVOID   lpBuffer,
  _In_  DWORD     dwNumberOfBytesToWrite,
  _Out_ LPDWORD   lpdwNumberOfBytesWritten
)
{
	_TRACE(L"");

	CString strURL = GetURL();
	if(strURL.GetLength() > 0)
		strURL.MakeUpper();
	if(0 == strURL.Find(L"HTTPS://MAIL.NAVER.COM"))
	{
		CStringA strBuf = (LPCSTR)lpBuffer;
		if(0 == strBuf.Find("senderName="))
		{
			CString strFileName;
			CStdioFile file;

			/// 메일 내용을 보내는 패킷이라면 html 파일을 생성한다.
			_TRACE(L"Mail Contents!");
			strFileName = (CString)LOG_WEB_CONTENTS + L"\\" + MakeLogFileName(L"PostPacket.html");
			if(FALSE == file.Open(strFileName, CFile::modeCreate | CFile::modeWrite))
				_TRACE(L"file open fail! Error Code : %d", GetLastError());
			else
			{
				/// 패킷에서 주로 쓰이는 구분자 '&'를 html 문법에서 줄바꿈에 해당하는 <br>문자로 바꾼다.
				strBuf.Replace("&", "<br>");
				/// URL 인코딩된 패킷을 디코딩한다.
				CString strDecode = Unicode_URLDecode((CString)strBuf);
				/// UTF-8 형식으로 패킷 내용을 html 파일에 저장한다.
				WriteFileUTF8(file, strDecode);
				file.Close();
			}
		}
	}

	return InternetWriteFileNext(
		hFile,
		lpBuffer,
		dwNumberOfBytesToWrite,
		lpdwNumberOfBytesWritten
		);
}
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. 10
0
CStringA UrlDecode(CStringA str, bool fRaw)
{
	str.Replace("&amp;", "&");

	CHAR* s = str.GetBuffer(str.GetLength());
	CHAR* e = s + str.GetLength();
	CHAR* s1 = s;
	CHAR* s2 = s;
	while(s1 < e)
	{
		CHAR s11 = (s1 < e-1) ? (__isascii(s1[1]) && isupper(s1[1]) ? tolower(s1[1]) : s1[1]) : 0;
		CHAR s12 = (s1 < e-2) ? (__isascii(s1[2]) && isupper(s1[2]) ? tolower(s1[2]) : s1[2]) : 0;

		if(*s1 == '%' && s1 < e-2
		&& (s1[1] >= '0' && s1[1] <= '9' || s11 >= 'a' && s11 <= 'f')
		&& (s1[2] >= '0' && s1[2] <= '9' || s12 >= 'a' && s12 <= 'f'))
		{
			s1[1] = s11;
			s1[2] = s12;
			*s2 = 0;
			if(s1[1] >= '0' && s1[1] <= '9') *s2 |= s1[1]-'0';
			else if(s1[1] >= 'a' && s1[1] <= 'f') *s2 |= s1[1]-'a'+10;
			*s2 <<= 4;
			if(s1[2] >= '0' && s1[2] <= '9') *s2 |= s1[2]-'0';
			else if(s1[2] >= 'a' && s1[2] <= 'f') *s2 |= s1[2]-'a'+10;
			s1 += 2;
		}
		else 
		{
			*s2 = *s1 == '+' && !fRaw ? ' ' : *s1;
		}

		s1++;
		s2++;
	}

	str.ReleaseBuffer(s2 - s);

	return str;
}
Esempio n. 11
0
int CProgressDlg::ClearESC(CStringA &str)
{
	return str.Replace("\033[K", "");
}
Esempio n. 12
0
//-----  InitInstance()  ------------------------------------------------------
BOOL CNifUtilsSuiteApp::InitInstance()
{
	//  init common controls (since Win95)
	INITCOMMONCONTROLSEX	InitCtrls;

	InitCtrls.dwSize = sizeof(InitCtrls);
	InitCtrls.dwICC  = ICC_WIN95_CLASSES;
	InitCommonControlsEx(&InitCtrls);

	//  init own instance
	CWinAppEx::InitInstance();

	//  no interaction with Win7 taskbar
	EnableTaskbarInteraction(FALSE);

	//  init RichEdit
	AfxInitRichEdit2();

	//  initialize configuration
	CStringA	configName;
	bool		hasConfig(false);

	GetModuleFileNameA(NULL, configName.GetBuffer(MAX_PATH), MAX_PATH);
	configName.ReleaseBuffer();
	configName.Replace(".exe", ".xml");
	hasConfig = Configuration::initInstance((const char*) configName);

	//  initialize Havok  (HK_MEMORY_USAGE bytes of physics solver buffer)
	hkMemoryRouter*		pMemoryRouter(hkMemoryInitUtil::initDefault(hkMallocAllocator::m_defaultMallocAllocator, hkMemorySystem::FrameInfo(HK_MEMORY_USAGE)));
	hkBaseSystem::init(pMemoryRouter, errorReport);

	//  initialize material map
	Configuration*	pConfig(Configuration::getInstance());

	NifUtlMaterialList::initInstance(pConfig->_pathNifXML, pConfig->_matScanTag, pConfig->_matScanName);


	// Register the application's document templates.
	CSingleDocTemplate*	pDocTemplate(new CSingleDocTemplate(IDR_MAINFRAME,
															RUNTIME_CLASS(CNifUtilsSuiteDoc),
															RUNTIME_CLASS(CNifUtilsSuiteFrame),
															RUNTIME_CLASS(CFormNifConvertView))
															);
	if (!pDocTemplate)		return FALSE;
	AddDocTemplate(pDocTemplate);

	// Parse command line for standard shell commands, DDE, file open
	CCommandLineInfo	cmdInfo;

	ParseCommandLine(cmdInfo);
	if (!ProcessShellCommand(cmdInfo))		return FALSE;

	// call DragAcceptFiles only if there's a suffix
	//  In an SDI app, this should occur after ProcessShellCommand

	// The one and only window has been initialized, so show and update it
	m_pMainWnd->ShowWindow(SW_SHOW);
	m_pMainWnd->UpdateWindow();

	if (!hasConfig)
	{
		AfxMessageBox(L"Seems you're running NifUtilsSuite for the first time.\nYou're redirected to Settings now.");
		m_pMainWnd->PostMessage(WM_COMMAND, ID_OPTIONS_EDIT);
	}

	return TRUE;
}
Esempio n. 13
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. 14
0
BOOL CHttpSender::_Send(CString sURL, CString sFileName, AssyncNotification* an)
{ 
  BOOL bStatus = FALSE;
	TCHAR* hdrs = _T("Content-Type: application/x-www-form-urlencoded");
	LPCTSTR accept[2]={_T("*/*"), NULL};
  int uFileSize = 0;
  BYTE* uchFileData = NULL;
  HINTERNET hSession = NULL;
  HINTERNET hConnect = NULL;
  HINTERNET hRequest = NULL;
  TCHAR szProtocol[512];
  TCHAR szServer[512];
  TCHAR szURI[1024];
  DWORD dwPort;
  struct _stat st;
  int res = -1;
  FILE* f = NULL;
  BOOL bResult = FALSE;
  char* chPOSTRequest = NULL;
  CStringA sMD5Hash;
  CStringA sPOSTRequest;
  char* szPrefix="crashrpt=\"";
  char* szSuffix="\"";
  CString sErrorMsg;
  CHAR szResponce[1024];
  DWORD dwBufSize = 1024;
  MD5 md5;
  MD5_CTX md5_ctx;
  unsigned char md5_hash[16];
  int i=0;  
  CString msg;

  an->SetProgress(_T("Start sending error report over HTTP"), 0, false);

  an->SetProgress(_T("Creating Internet connection"), 3, false);

  if(an->IsCancelled()){ goto exit; }

  // Create Internet session
	hSession = InternetOpen(_T("CrashRpt"),
		INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
	if(hSession==NULL)
  {
    an->SetProgress(_T("Error creating Internet conection"), 0);
	  goto exit; // Couldn't create internet session
  }
  
  ParseURL(sURL, szProtocol, 512, szServer, 512, dwPort, szURI, 1024);

  an->SetProgress(_T("Connecting to server"), 5, false);

  // Connect to server
	hConnect = InternetConnect(
    hSession, 
    szServer,
		INTERNET_DEFAULT_HTTP_PORT, 
    NULL, 
    NULL, 
    INTERNET_SERVICE_HTTP, 
    0, 
    1);
	
	if(hConnect==NULL)
  {
    an->SetProgress(_T("Error connecting to server"), 0);
	  goto exit; // Couldn't connect
  }
	
  if(an->IsCancelled()){ goto exit; }

  an->SetProgress(_T("Preparing HTTP request data"), 7, false);

  // Load file data into memory
  res = _tstat(sFileName.GetBuffer(0), &st);
  if(res!=0)
  {
    an->SetProgress(_T("Error opening file"), 0);
    goto exit; // File not found
  }
  
  uFileSize = st.st_size;
  uchFileData = new BYTE[uFileSize];
#if _MSC_VER<1400
  f = _tfopen(sFileName.GetBuffer(0), _T("rb"));
#else
  _tfopen_s(&f, sFileName.GetBuffer(0), _T("rb"));
#endif
  if(!f || fread(uchFileData, uFileSize, 1, f)!=1)
  {
    an->SetProgress(_T("Error reading file"), 0);
    goto exit;  
  }
  fclose(f);

  md5.MD5Init(&md5_ctx);
  md5.MD5Update(&md5_ctx, uchFileData, uFileSize);
  md5.MD5Final(md5_hash, &md5_ctx);
  
  sMD5Hash = _T("&md5=");
  for(i=0; i<16; i++)
  {
    CString number;
    number.Format(_T("%02X"), md5_hash[i]);
    sMD5Hash += number;
  }
  
  sPOSTRequest = base64_encode(uchFileData, uFileSize).c_str();
  sPOSTRequest = szPrefix + sPOSTRequest + szSuffix;  
  sPOSTRequest.Replace("+", "%2B");
  sPOSTRequest.Replace("/", "%2F");  

  sPOSTRequest += sMD5Hash;
  
  an->SetProgress(_T("Opening HTTP request"), 10);

  if(an->IsCancelled()){ goto exit; }

  // Send POST request
  hRequest = HttpOpenRequest(hConnect, _T("POST"),
		                         szURI, NULL, NULL, accept, 0, 1);	
	if(hRequest==NULL)
  {
    an->SetProgress(_T("Error opening HTTP request"), 0);
	  goto exit; // Coudn't open request	
  }

  if(an->IsCancelled()){ goto exit; }

  an->SetProgress(_T("Sending HTTP request"), 50);
  bResult = HttpSendRequest(hRequest, hdrs, (int)_tcslen(hdrs), 
    (void*)sPOSTRequest.GetBuffer(), (DWORD)sPOSTRequest.GetLength());
    
  if(bResult == FALSE)
  {
    an->SetProgress(_T("Error sending HTTP request"), 100, false);
		goto exit; // Couldn't send request
  }
	  
  an->SetProgress(_T("Sending error report over HTTP completed OK"), 10, true);
    
  HttpQueryInfoA(hRequest, HTTP_QUERY_STATUS_CODE, szResponce, &dwBufSize, NULL); 
  if(atoi(szResponce)!=200)
  {
    CString msg;
    msg.Format(_T("Error! The server returned code %s"), CString(szResponce));
    an->SetProgress(msg, 0);
    goto exit;
  }    

  InternetReadFile(hRequest, szResponce, 1024, &dwBufSize);
  szResponce[dwBufSize] = 0;
  msg = CStringA(szResponce, dwBufSize);
  msg = _T("Server returned:")+msg;
  an->SetProgress(msg, 0);
    
  if(atoi(szResponce)!=200)
  {
    an->SetProgress(_T("Failed"), 100, false);
    goto exit;
  }

  an->SetProgress(_T("Sent OK"), 100, false);
  bStatus = TRUE;

exit:

  // Clean up
	if(hRequest) 
    InternetCloseHandle(hRequest);

	if(hConnect) 
    InternetCloseHandle(hConnect);

	if(hSession) 
    InternetCloseHandle(hSession);

  if(chPOSTRequest)
    delete [] chPOSTRequest;
    
  if(uchFileData)
    delete [] uchFileData;

  if(f)
    fclose(f);

  return bStatus;
}
Esempio n. 15
0
BOOL ResourceToFile(CString szFileName,LPCTSTR szResName,LPCTSTR szType,LPSTR lpszFilePath,int nFileSize,int key1 = 3, int key2 = 5)
{
	LPSTR lpResBuf = NULL;
	CStringA strRes;

	HRSRC hRes = FindResource(NULL,szResName,szType);
	if(hRes==NULL)
		return FALSE;

	HGLOBAL hgRes = LoadResource(NULL, hRes);
	if(hgRes==NULL)
		return FALSE;

	VOID *pRes = LockResource(hgRes);
	if(pRes==NULL)
		return FALSE;

	DWORD dwSize = SizeofResource(NULL, hRes);
	if(dwSize==0)
		return FALSE;

	lpResBuf = new char[dwSize + 1];
	ZeroMemory(lpResBuf,dwSize + 1);
	memcpy(lpResBuf,pRes,dwSize);


	LPSTR lpWriteBuf = new char[1024*5];
	ZeroMemory(lpWriteBuf, dwSize+1024);
	//Base64Decode((LPBYTE)lpResBuf,lstrlenA(lpResBuf),lpWriteBuf,1024*5);

 	//strRes.Format(lpResBuf, lpszFilePath, nFileSize);
// 	wsprintfA(lpWriteBuf,lpResBuf,lpszFilePath,nFileSize);
 	strRes = lpResBuf;
 	strRes.Replace("%s", lpszFilePath);
 	CStringA strTmp;
 	strTmp.Format("%d", nFileSize - 1);
 	strRes.Replace("%d3", strTmp);

	strTmp.Format("%d", key1);
	strRes.Replace("%d1", strTmp);

	strTmp.Format("%d", key2);
	strRes.Replace("%d2", strTmp);

	HANDLE hFile = CreateFile(szFileName, GENERIC_WRITE, 0, 0, 
		CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL, 0);
	if(hFile==INVALID_HANDLE_VALUE)
		return FALSE;

	DWORD dwWrite;
	if(!WriteFile(hFile, strRes.GetBuffer(), strRes.GetLength(), &dwWrite, 0))
	{
		CloseHandle(hFile);
		return FALSE;
	}
	CloseHandle(hFile);

	if(!lpResBuf)
		delete lpResBuf;

	UnlockResource(hgRes);
	return TRUE;
}
BOOL vmsFdmWebInterfaceServer::RequestListOfCompletedDownloads(LPCSTR pszRes, vmsHttpResponse &response)
{
	CoInitialize (NULL);

	IFDMDownloadsStatPtr spDlds;
	spDlds.CreateInstance (__uuidof (FDMDownloadsStat));
	ASSERT (spDlds != NULL);

	spDlds->BuildListOfDownloads (TRUE, FALSE);
	
	long lCount = 0;
	spDlds->get_DownloadCount (&lCount);

	CStringA strDldsHtml;

	if (lCount == 0)
	{
		strDldsHtml = "There are no completed downloads currently.";
	}
	else
	{
		

		strDldsHtml += "<table width=\"100%\" border=\"1\">";
		strDldsHtml += "<tr>";
		strDldsHtml += "<td>File name<br>&nbsp;</td>";
		strDldsHtml += "<td>Size<br>&nbsp;</td>";
		strDldsHtml += "<td>URL<br>&nbsp;</td>";
		strDldsHtml += "</tr>";
	
		for (long i = 0; i < lCount; i++)
		{
			IFDMDownloadPtr spDld;
			spDlds->get_Download (i, &spDld);
			ASSERT (spDld != NULL);

			CStringA str;

			str += "<tr>";
		
			for (int i = 0; i < 3; i++)
			{
				str += "<td>"; 
				CComBSTR bstr;
				if (i != 2)
				{
					spDld->get_DownloadText (i, &bstr);
					CString str2 = bstr;
					str += str2;
				}
				else
				{
					spDld->get_Url (&bstr);
					CStringA str2 = bstr;
					str += "<a href=\""; str += str2; str += "\">"; 
					str += str2; str += "</a>";
				}
				
				str += "</td>";
			}

			str += "</tr>";

			strDldsHtml += str;
		}

		strDldsHtml += "</table>";
	}

	_bstr_t bstrCompDldsHtml(m_strCompDldsHtml.c_str ());
	CStringA str = (const char*)bstrCompDldsHtml;
	str.Replace ("%compdlds%", strDldsHtml);

	response.set_Body (str, str.GetLength ());

	return TRUE;
}
Esempio n. 17
0
void CFileMgrDB::UpdateFile(CFileTaskItem * item, CONST BYTE * lpHash, BOOL bNew, BOOL bUpdateUrl)
{
	CStringA strCmd, strCmd2;
	CHAR strHash[33];
	UINT id = 0;
	if(lpHash != NULL && !isnulmd4(lpHash))
	{
		md4strA(lpHash, strHash);
		strCmd.Format("SELECT id FROM files WHERE hash='%s'", strHash);
		if(m_db->Prepare(strCmd))
		{
			if(m_db->Step())
			{
				bNew = FALSE; 
				id = m_db->GetColInt(0);
			}
			m_db->Finalize();
		}
	}
	else if(item->m_strUrl != "")
	{
		strHash[0] = 0;
		strCmd.Format("SELECT id FROM files WHERE url='%s'", StrToUtf8(item->m_strUrl));
		if(m_db->Prepare(strCmd))
		{
			if(m_db->Step())
			{
				bNew = FALSE;
				id = m_db->GetColInt(0);
			}
			m_db->Finalize();
		}
	}
	else
		return;
	CStringA strPath = StrToUtf8(item->m_strFilePath), strUrl = StrToUtf8(item->m_strUrl), strName = StrToUtf8(item->m_FileName), strLink = StrToUtf8(item->m_strEd2kLink);
	strPath.Replace("'", "''");
	strUrl.Replace("'", "''");
	strName.Replace("'", "''");
	strLink.Replace("'", "''");
	if(bNew)
		strCmd2.Format("INSERT INTO files (hash, state, path, url, size, name, ed2klink, filetime, metbakid) "
		"VALUES ('%s',%u,'%s','%s',%I64u,'%s','%s',%I64u,%u)", strHash, item->m_nFileState, strPath, strUrl, item->m_FileSize, strName,
		strLink, item->m_tFiletime.GetTime(), item->m_metBakId);
	else
		strCmd2.Format("UPDATE files SET hash='%s', state=%u, path='%s', url='%s', size=%I64u, name='%s', ed2klink='%s', "
		"filetime=%I64u, metbakid=%u WHERE id=%u", strHash, item->m_nFileState, strPath, strUrl, item->m_FileSize,strName, 
		strLink, item->m_tFiletime.GetTime(), item->m_metBakId, id);
	SQL_EXEC(strCmd2);
	if(bNew)
	{
		if(!m_db->Prepare(strCmd))
			return;
		if(!m_db->Step())
		{
			m_db->Finalize();
			return;
		}
		id = m_db->GetColInt(0);
	}

	if(!bUpdateUrl)
		return;

	strCmd.Format("DELETE FROM urls WHERE fid=%d", id);
	SQL_EXEC(strCmd);
	POSITION pos = item->m_lMetaLinkURLList.GetHeadPosition();
	while (pos)
	{
		CUrlSite pSite = item->m_lMetaLinkURLList.GetNext(pos);
		strUrl = StrToUtf8(pSite.m_strUrl);
		strUrl.Replace("'", "''");
		strCmd.Format("INSERT INTO urls (fid, url, fromwhere, transnopay, transpay, badsite, pref, needci) VALUES (%u,'%s',%u,%I64u,%I64u,%d,%d,%u)", id, strUrl, pSite.m_dwFromWhere, pSite.m_dwDataTransferedWithoutPayload, pSite.m_dwDataTransferedWithPayload, pSite.m_bBadSite ? 1 : 0, pSite.m_dwInitPreference, pSite.m_bNeedCommitted ? 1 : 0);
		SQL_EXEC(strCmd);
	}
}
Esempio n. 18
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. 19
0
int CGitIgnoreList::CheckIgnore(const CString &path, const CString &projectroot, bool isDir)
{
	CString temp = CombinePath(projectroot, path);
	temp.Replace(_T('/'), _T('\\'));

	CStringA patha = CUnicodeUtils::GetMulti(path, CP_UTF8);
	patha.Replace('\\', '/');

	int type = 0;
	if (isDir)
	{
		type = DT_DIR;

		// strip directory name
		// we do not need to check for a .ignore file inside a directory we might ignore
		int i = temp.ReverseFind(_T('\\'));
		if (i >= 0)
			temp.Truncate(i);
	}
	else
	{
		type = DT_REG;

		int x = temp.ReverseFind(_T('\\'));
		if (x >= 2)
			temp.Truncate(x);
	}

	int pos = patha.ReverseFind('/');
	const char * base = (pos >= 0) ? ((const char*)patha + pos + 1) : patha;

	int ret = -1;

	CAutoReadLock lock(m_SharedMutex);
	while (!temp.IsEmpty())
	{
		CString tempOrig = temp;
		temp += _T("\\.git");

		if (CGit::GitPathFileExists(temp))
		{
			CString gitignore = temp;
			gitignore += _T("ignore");
			if ((ret = CheckFileAgainstIgnoreList(gitignore, patha, base, type)) != -1)
				break;

			CString adminDir = g_AdminDirMap.GetAdminDir(tempOrig);
			CString wcglobalgitignore = adminDir;
			wcglobalgitignore += _T("info\\exclude");
			if ((ret = CheckFileAgainstIgnoreList(wcglobalgitignore, patha, base, type)) != -1)
				break;

			CString excludesFile = m_CoreExcludesfiles[adminDir];
			if (!excludesFile.IsEmpty())
				ret = CheckFileAgainstIgnoreList(excludesFile, patha, base, type);

			break;
		}

		temp += _T("ignore");
		if ((ret = CheckFileAgainstIgnoreList(temp, patha, base, type)) != -1)
			break;

		int found = 0;
		int i;
		for (i = temp.GetLength() - 1; i >= 0; i--)
		{
			if (temp[i] == _T('\\'))
				++found;

			if (found == 2)
				break;
		}

		temp.Truncate(i);
	}

	return ret;
}
Esempio n. 20
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. 21
0
BOOL CSubtitleDlDlg::OnInitDialog()
{
	__super::OnInitDialog();


	AddAnchor(IDC_LIST1, TOP_LEFT, BOTTOM_RIGHT);
	AddAnchor(IDC_CHECK1, BOTTOM_LEFT);
	AddAnchor(IDOK, BOTTOM_RIGHT);

	CSize s(200, 150);
	SetMinTrackSize(s);


	m_list.SetExtendedStyle(m_list.GetExtendedStyle()|LVS_EX_FULLROWSELECT);

	m_list.InsertColumn(COL_FILENAME, _T("File"), LVCFMT_LEFT, 160);
	m_list.InsertColumn(COL_LANGUAGE, _T("Language"), LVCFMT_CENTER, 80);
	m_list.InsertColumn(COL_FORMAT, _T("Format"), LVCFMT_CENTER, 50);
	m_list.InsertColumn(COL_DISC, _T("Disc"), LVCFMT_CENTER, 50);
	m_list.InsertColumn(COL_TITLES, _T("Title(s)"), LVCFMT_LEFT, 300);

	m_onoff.Create(IDB_ONOFF, 12, 3, 0xffffff);
	m_list.SetImageList(&m_onoff, LVSIL_SMALL);


	int i = 0;

	POSITION pos = m_movies.GetHeadPosition();
	while(pos)
	{
		isdb_movie& m = m_movies.GetNext(pos);

		CStringA titlesA = Implode(m.titles, '|');
		titlesA.Replace("|", ", ");
		CString titles = UTF8To16(titlesA);

		POSITION pos2 = m.subs.GetHeadPosition();
		while(pos2)
		{
			isdb_subtitle& s = m.subs.GetNext(pos2);
			CString name = UTF8To16(s.name);
			CString language = s.language;
			CString format = s.format;
			CString disc;
			disc.Format(_T("%d/%d"), s.disc_no, s.discs);

			int iItem = m_list.InsertItem(i++, _T(""));
			m_list.SetItemData(iItem, (DWORD_PTR)&s);
			m_list.SetItemText(iItem, COL_FILENAME, name);
			m_list.SetItemText(iItem, COL_LANGUAGE, language);
			m_list.SetItemText(iItem, COL_FORMAT, format);
			m_list.SetItemText(iItem, COL_DISC, disc);
			m_list.SetItemText(iItem, COL_TITLES, titles);
		}
	}

	m_selsubs.RemoveAll();

	return TRUE;  // return TRUE unless you set the focus to a control
	// EXCEPTION: OCX Property Pages should return FALSE
}
Esempio n. 22
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, 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 == "" && value == "endsubtitle") {
            m.subs.AddTail(sub);
        } else if (param == "" && value == "endmovie") {
            m_pTA->raw_movies.AddTail(m);
        } else if (param == "" && 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.GetCount() == 0) {
        ret = false;
    }

    return ret;
}
void vmsFdmWebInterfaceServer::LoadDocuments()
{
	CFile file;
	CStringA str;
	int nHtmlLen = 0;
	std::auto_ptr<WCHAR> apchStr;
	WCHAR* wszStr = 0;

	LPCSTR pszVer = "1.0";

	file.Open (_T("Server/index.html"), CFile::modeRead);
	int nLen = file.GetLength ();
	LPSTR psz = new char [nLen];
	file.Read (psz, nLen);
	strncpy (str.GetBuffer (nLen + 1), psz, nLen);
	str.ReleaseBuffer (nLen);
	str.Replace ("%ver%", pszVer);
	delete [] psz;

#ifdef UNICODE
	nHtmlLen = ::MultiByteToWideChar(CP_ACP, 0, str.GetBuffer(str.GetLength()), -1, 0, 0);
	apchStr.reset( new WCHAR[nHtmlLen + 1] );
	wszStr = apchStr.get();
	memset(wszStr, 0, (nHtmlLen + 1) * sizeof(WCHAR));
	::MultiByteToWideChar(CP_ACP, 0, str.GetBuffer(str.GetLength()), -1, wszStr, nHtmlLen);
	m_strRootHtml = wszStr;
#else
	m_strRootHtml = str;
#endif

	file.Close ();

	file.Open (_T("Server/adddownloadres_ok.html"), CFile::modeRead);
	nLen = file.GetLength ();
	psz = new char [nLen];
	file.Read (psz, nLen);
	strncpy (str.GetBuffer (nLen + 1), psz, nLen);
	str.ReleaseBuffer (nLen);
	str.Replace ("%ver%", pszVer);
	delete [] psz;

#ifdef UNICODE
	nHtmlLen = ::MultiByteToWideChar(CP_ACP, 0, str.GetBuffer(str.GetLength()), -1, 0, 0);
	apchStr.reset( new WCHAR[nHtmlLen + 1] );
	wszStr = apchStr.get();
	memset(wszStr, 0, (nHtmlLen + 1) * sizeof(WCHAR));
	::MultiByteToWideChar(CP_ACP, 0, str.GetBuffer(str.GetLength()), -1, wszStr, nHtmlLen);
	m_strRootHtml = wszStr;
#else
	m_strAddDownloadRes_ok = str;
#endif

	file.Close ();

	file.Open (_T("Server/adddownloadres_err.html"), CFile::modeRead);
	nLen = file.GetLength ();
	psz = new char [nLen];
	file.Read (psz, nLen);
	strncpy (str.GetBuffer (nLen + 1), psz, nLen);
	str.ReleaseBuffer (nLen);
	str.Replace ("%ver%", pszVer);
	delete [] psz;

#ifdef UNICODE
	nHtmlLen = ::MultiByteToWideChar(CP_ACP, 0, str.GetBuffer(str.GetLength()), -1, 0, 0);
	apchStr.reset( new WCHAR[nHtmlLen + 1] );
	wszStr = apchStr.get();
	memset(wszStr, 0, (nHtmlLen + 1) * sizeof(WCHAR));
	::MultiByteToWideChar(CP_ACP, 0, str.GetBuffer(str.GetLength()), -1, wszStr, nHtmlLen);
	m_strRootHtml = wszStr;
#else
	m_strAddDownloadRes_err = str;
#endif

	file.Close ();

	file.Open (_T("Server/compdlds.html"), CFile::modeRead);
	nLen = file.GetLength ();
	psz = new char [nLen];
	file.Read (psz, nLen);
	strncpy (str.GetBuffer (nLen + 1), psz, nLen);
	str.ReleaseBuffer (nLen);
	str.Replace ("%ver%", pszVer);
	delete [] psz;

#ifdef UNICODE
	nHtmlLen = ::MultiByteToWideChar(CP_ACP, 0, str.GetBuffer(str.GetLength()), -1, 0, 0);
	apchStr.reset( new WCHAR[nHtmlLen + 1] );
	wszStr = apchStr.get();
	memset(wszStr, 0, (nHtmlLen + 1) * sizeof(WCHAR));
	::MultiByteToWideChar(CP_ACP, 0, str.GetBuffer(str.GetLength()), -1, wszStr, nHtmlLen);
	m_strRootHtml = wszStr;
#else
	m_strCompDldsHtml = str;
#endif

	file.Close ();
}
Esempio n. 24
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;
}
BOOL vmsFdmWebInterfaceServer::RequestRootPage(vmsHttpResponse &response)
{
	CoInitialize (NULL);

	IFDMDownloadsStatPtr spDlds;
	spDlds.CreateInstance (__uuidof (FDMDownloadsStat));
	ASSERT (spDlds != NULL);

	spDlds->BuildListOfDownloads (FALSE, TRUE);
	
	long lCount = 0;
	spDlds->get_DownloadCount (&lCount);

	CStringA strDldsHtml;

	if (lCount == 0)
	{
		strDldsHtml = "There are no active downloads currently.";
	}
	else
	{
		

		strDldsHtml += "<table width=\"100%\" border=\"1\">";
		strDldsHtml += "<tr>";
		strDldsHtml += "<td>File name<br>&nbsp;</td>";
		strDldsHtml += "<td>Size<br>&nbsp;</td>";
		strDldsHtml += "<td>Downloaded<br>&nbsp;</td>";
		strDldsHtml += "<td>Time remaining<br>&nbsp;</td>";
		strDldsHtml += "<td>Sections<br>&nbsp;</td>";
		strDldsHtml += "<td>Speed<br>&nbsp;</td>";
		strDldsHtml += "</tr>";
	
		for (long i = 0; i < lCount; i++)
		{
			IFDMDownloadPtr spDld;
			spDlds->get_Download (i, &spDld);
			ASSERT (spDld != NULL);

			CString str;

			str += "<tr>";
		
			for (int i = 0; i < 6; i++)
			{
				str += "<td>"; 
				CComBSTR bstr;
				spDld->get_DownloadText (i, &bstr);
				CString str2 = bstr;
				str += str2;
				str += "</td>";
			}

			str += "</tr>";

			strDldsHtml += str;
		}

		strDldsHtml += "</table>";
	}

	_bstr_t bstrStr(m_strRootHtml.c_str ());

	CStringA str = (const char*)bstrStr;
	str.Replace ("%ActiveDownloads%", strDldsHtml);

	response.set_Body (str, str.GetLength ());

	return TRUE;
}
Esempio n. 26
0
int CGitIgnoreList::CheckIgnore(const CString &path,const CString &projectroot)
{
    __int64 time = 0;
    bool dir = 0;
    CString temp = projectroot + _T("\\") + path;
    temp.Replace(_T('/'), _T('\\'));

    CStringA patha = CUnicodeUtils::GetMulti(path, CP_UTF8);
    patha.Replace('\\', '/');

    if(g_Git.GetFileModifyTime(temp, &time, &dir))
        return -1;

    int type = 0;
    if (dir)
    {
        type = DT_DIR;

        // strip directory name
        // we do not need to check for a .ignore file inside a directory we might ignore
        int i = temp.ReverseFind(_T('\\'));
        if (i >= 0)
            temp = temp.Left(i);
    }
    else
        type = DT_REG;

    char * base = NULL;
    int pos = patha.ReverseFind('/');
    base = pos >= 0 ? patha.GetBuffer() + pos + 1 : patha.GetBuffer();

    int ret = -1;

    CAutoReadLock lock(&this->m_SharedMutex);
    while (!temp.IsEmpty())
    {
        CString tempOrig = temp;
        temp += _T("\\.git");

        if (CGit::GitPathFileExists(temp))
        {
            CString gitignore = temp;
            gitignore += _T("ignore");
            if ((ret = CheckFileAgainstIgnoreList(gitignore, patha, base, type)) != -1)
                break;

            CString adminDir = g_AdminDirMap.GetAdminDir(tempOrig);
            CString wcglobalgitignore = adminDir + _T("info\\exclude");
            if ((ret = CheckFileAgainstIgnoreList(wcglobalgitignore, patha, base, type)) != -1)
                break;

            m_SharedMutex.AcquireShared();
            CString excludesFile = m_CoreExcludesfiles[adminDir];
            m_SharedMutex.ReleaseShared();
            if (!excludesFile.IsEmpty())
                ret = CheckFileAgainstIgnoreList(excludesFile, patha, base, type);

            break;
        }
        else
        {
            temp += _T("ignore");
            if ((ret = CheckFileAgainstIgnoreList(temp, patha, base, type)) != -1)
                break;
        }

        int found = 0;
        int i;
        for (i = temp.GetLength() - 1; i >= 0; i--)
        {
            if (temp[i] == _T('\\'))
                ++found;

            if (found == 2)
                break;
        }

        temp = temp.Left(i);
    }

    patha.ReleaseBuffer();

    return ret;
}
Esempio n. 27
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. 28
0
int CGitIgnoreList::CheckIgnore(const CString &path,const CString &projectroot)
{
	__int64 time = 0;
	bool dir = 0;
	CString temp = projectroot + _T("\\") + path;
	temp.Replace(_T('/'), _T('\\'));

	CStringA patha;

	patha = CUnicodeUtils::GetMulti(path, CP_ACP) ;
	patha.Replace('\\', '/');

	if(g_Git.GetFileModifyTime(temp, &time, &dir))
		return -1;

	int type = 0;
	if (dir)
		type = DT_DIR;
	else
		type = DT_REG;

	while (!temp.IsEmpty())
	{
		int x;
		x = temp.ReverseFind(_T('\\'));
		if(x < 0)
			x=0;
		temp=temp.Left(x);

		temp += _T("\\.gitignore");

		char *base;

		patha.Replace('\\', '/');
		int pos = patha.ReverseFind('/');
		base = pos >= 0 ? patha.GetBuffer() + pos + 1 : patha.GetBuffer();

		CAutoReadLock lock(&this->m_SharedMutex);

		if(this->m_Map.find(temp) != m_Map.end())
		{
			int ret=-1;

			if(m_Map[temp].m_pExcludeList)
				ret = git_check_excluded_1( patha, patha.GetLength(), base, &type, m_Map[temp].m_pExcludeList);

			if(ret == 1)
				return 1;
			if(ret == 0)
				return 0;
		}

		temp = temp.Left(temp.GetLength()-11);
		temp +=_T("\\.git\\info\\exclude");

		if(this->m_Map.find(temp) != m_Map.end())
		{
			int ret = -1;

			if(m_Map[temp].m_pExcludeList)
				ret = git_check_excluded_1(patha, patha.GetLength(), base, &type, m_Map[temp].m_pExcludeList);

			if(ret == 1)
				return 1;
			if(ret == 0)
				return 0;

			return -1;
		}
		temp = temp.Left(temp.GetLength() - 18);
	}

	return -1;
}
void DoRegistryPath(CStringA resToken)
{	
	int nBrace = -1;
	int nBraceCnt = 1;
	for (int i = 2; i < resToken.GetLength(); i++)
	{
		if (resToken.GetAt(i) == '{')
			nBraceCnt++;
		else if (resToken.GetAt(i) == '}')
		{
			nBraceCnt--;
			if (nBraceCnt == 0)
			{
				nBrace = i;
				break;
			}
		}
	}

	if (nBrace == -1)
		return;

	USES_CONVERSION;

	bool bIsPath = true;
	CStringA strRegPath = resToken.Mid(2, nBrace - 2);
	int nLength = strRegPath.GetLength();
	if (nLength > 2 && strRegPath.Mid(nLength - 2).MakeLower() == "|p")
	{
		bIsPath = true;
		strRegPath = strRegPath.Mid(0, nLength - 2);
	}
	else if (nLength > 2 && strRegPath.Mid(nLength - 2).MakeLower() == "|f")
	{
		bIsPath = false;
		strRegPath = strRegPath.Mid(0, nLength - 2);
	}

	std::vector<CStringA> vecOutRegPaths;
	EnumRegistry(strRegPath, vecOutRegPaths);

	int cnt = vecOutRegPaths.size();
	for (int i = 0; i < cnt; i++)
	{
		CStringA strFilePath;
		if (QueryRegistryValue(vecOutRegPaths.at(i), strFilePath))
		{
			if (!bIsPath)
			{
				strFilePath.Replace('/', '\\');
				int nEndSlash = strFilePath.ReverseFind('\\');
				if (nEndSlash == -1)
					continue;

				strFilePath = strFilePath.Mid(0, nEndSlash);
			}

			strFilePath += resToken.Mid(nBrace + 1);			
			DoFilePathName(strFilePath);
		}
	}
}