예제 #1
0
파일: HttpFileSend.cpp 프로젝트: ACUVE/EDCB
void CHttpFileSend::GetContentType(wstring filePath, string& contentType)
{
	wstring ext = L"";
	GetFileExt(filePath, ext);

	wstring textPath;
	GetModuleFolderPath(textPath);
	textPath += L"\\ContentTypeText.txt";

	CParseContentTypeText contentTypeUtil;
	contentTypeUtil.ParseText(textPath.c_str());

	wstring typeW = L"";
	contentTypeUtil.GetMimeType(ext, typeW);
	WtoA(typeW, contentType);
}
예제 #2
0
static void initRelations()
{
	// clear state
	itemStateTable.clear();

	// reset checkbox state
	string datName;
	int nChecked = 0;

	for (int i = 0; i < nNumPatches; i++) {
		nChecked = _TreeView_GetCheckState(hIpsList, hPatchHandlesIndex[i]);
		datName = WtoA(szDataNames[i]);
		lowerString(datName);
		itemStateTable.insert(make_pair(datName, nChecked));
	}
}
예제 #3
0
/**
 * Open a file.
 * @param filename Filename.
 * @param mode File mode.
 * @return File pointer, or NULL on error.
 */
FILE *W32U_fopen(const char *filename, const char *mode)
{
	wchar_t *filenameW, *modeW;
	FILE *fRet;
	int errno_ret = 0;

	// Convert the arguments from UTF-8 to UTF-16.
	UtoW_filename(filename);
	UtoW(mode);
	if (!filenameW || !modeW) {
		errno = EINVAL;
		return NULL;
	}

	fRet = NULL;
	if (W32U_IsUnicode()) {
		// Unicode version.
		fRet = _wfopen(filenameW, modeW);
		errno_ret = errno;
	} else {
#ifdef ENABLE_ANSI_WINDOWS
		// ANSI version.
		// Convert the arguments from UTF-16 to ANSI.
		char *filenameA, *modeA;
		WtoA_filename(filename);
		WtoA(mode);
		if (!filenameA || !modeA) {
			errno_ret = EINVAL;
			goto fail;
		}

		// Open the file.
		fRet = fopen(filenameA, modeA);
#else /* !ENABLE_ANSI_WINDOWS */
		// ANSI is not supported in this build.
		// TODO: Fail earlier to avoid an alloc()?
		fRet = NULL;
		errno_ret = ENOSYS;
		goto fail; /* MSVC complains if a label is unreferenced. (C4102) */
#endif /* ENABLE_ANSI_WINDOWS */
	}

fail:
	errno = errno_ret;
	return fRet;
}
예제 #4
0
static HRESULT RuntimeHost_AddDomain(RuntimeHost *This, MonoDomain **result)
{
    struct DomainEntry *entry;
    char *mscorlib_path;
    HRESULT res=S_OK;

    EnterCriticalSection(&This->lock);

    entry = HeapAlloc(GetProcessHeap(), 0, sizeof(*entry));
    if (!entry)
    {
        res = E_OUTOFMEMORY;
        goto end;
    }

    mscorlib_path = WtoA(This->version->mscorlib_path);
    if (!mscorlib_path)
    {
        HeapFree(GetProcessHeap(), 0, entry);
        res = E_OUTOFMEMORY;
        goto end;
    }

    entry->domain = This->mono->mono_jit_init(mscorlib_path);

    HeapFree(GetProcessHeap(), 0, mscorlib_path);

    if (!entry->domain)
    {
        HeapFree(GetProcessHeap(), 0, entry);
        res = E_FAIL;
        goto end;
    }

    This->mono->is_started = TRUE;

    list_add_tail(&This->domains, &entry->entry);

    *result = entry->domain;

end:
    LeaveCriticalSection(&This->lock);

    return res;
}
예제 #5
0
char *U8toA(const char *src, BOOL noStatic) {
	static	char	*_buf = NULL;

	char	*tmp = NULL;
	char	*&buf = noStatic ? tmp : _buf;

	if (buf) {
		delete [] buf;
		buf = NULL;
	}

	WCHAR	*wsrc = U8toW(src, TRUE);
	if (wsrc) {
		buf = WtoA(wsrc, TRUE);
	}
	delete [] wsrc;
	return	buf;
}
예제 #6
0
void CTunerBankCtrl::SaveProgramInfo(LPCWSTR recPath, const EPGDB_EVENT_INFO& info, bool append) const
{
	wstring iniCommonPath;
	GetCommonIniPath(iniCommonPath);
	wstring infoFolder = GetPrivateProfileToString(L"SET", L"RecInfoFolder", L"", iniCommonPath.c_str());
	ChkFolderPath(infoFolder);

	wstring savePath;
	if( infoFolder.empty() ){
		savePath = recPath;
	}else{
		GetFileName(recPath, savePath);
		savePath = infoFolder + L"\\" + savePath;
	}
	savePath += L".program.txt";

	wstring serviceName;
	for( size_t i = 0; i < this->chList.size(); i++ ){
		if( this->chList[i].originalNetworkID == info.original_network_id &&
		    this->chList[i].transportStreamID == info.transport_stream_id &&
		    this->chList[i].serviceID == info.service_id ){
			serviceName = this->chList[i].serviceName;
			break;
		}
	}
	wstring outTextW;
	_ConvertEpgInfoText2(&info, outTextW, serviceName);
	string outText;
	WtoA(outTextW, outText);

	HANDLE hFile = _CreateDirectoryAndFile(savePath.c_str(), GENERIC_WRITE | GENERIC_READ, FILE_SHARE_READ, NULL, append ? OPEN_ALWAYS : CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
	if( hFile != INVALID_HANDLE_VALUE ){
		if( append ){
			SetFilePointer(hFile, 0, NULL, FILE_END);
			outText = "\r\n-----------------------\r\n" + outText;
		}
		DWORD dwWrite;
		WriteFile(hFile, outText.c_str(), (DWORD)outText.size(), &dwWrite, NULL);
		CloseHandle(hFile);
	}
}
예제 #7
0
int CHttpRecFileSend::SendRecFileList(nocase::map<string, string>* headerList, SOCKET clientSock, HANDLE stopEvent)
{
	int ret = 200;

	string sendHtml = "";
	string buff="";
	nocase::map<string, string> httpResHeader;

	sendHtml = HTML_TEXT_TOP;

	sendHtml+="録画ファイル一覧<BR>\r\n<BR>\r\n";

	if( this->recInfoList.size() == 0 ){
		sendHtml+="ファイルが存在しません<BR>\r\n";
	}else{
		map<DWORD, REC_FILE_INFO>::iterator itr;
		for(itr = this->recInfoList.begin(); itr != this->recInfoList.end(); itr++ ){
			string item="";
			wstring fileName = L"";
			string fileNameA = "";
			GetFileName(itr->second.recFilePath, fileName);
			WtoA(fileName, fileNameA);

			Format(item, "<a href=\".%s/%d\">%s</a><BR>\r\n", rootUri.c_str(), itr->second.id, fileNameA.c_str());
			sendHtml+=item;
		}
	}

	sendHtml += HTML_TEXT_END;

	Format(buff, "%I64d", sendHtml.size());
	httpResHeader.insert(pair<string, string>("Content-Length", buff));
	httpResHeader.insert(pair<string, string>("Content-Type", "text/html; charset=Shift_JIS;"));

	httpSend.SendResponseHeader(200, &httpResHeader, clientSock, stopEvent);
	httpSend.SendData((BYTE*)sendHtml.c_str(), (DWORD)sendHtml.size(), clientSock, stopEvent);

	return ret;
}
예제 #8
0
BOOL NetPlaceConvertV(void *src, void *dst)
{
	IShellLink		*shellLink;		// VC4 には IShellLink ANSI 版しか定義がないための暫定処置
	IPersistFile	*persistFile;	// (実際は NT系では IShellLinkW を呼び出し)
	WCHAR	wSrcBuf[MAX_PATH], wDstBuf[MAX_PATH];
	WCHAR	*wSrc = IS_WINNT_V ? (WCHAR *)src : wSrcBuf;
	WCHAR	*wDst = IS_WINNT_V ? wDstBuf : (WCHAR *)dst;
	BOOL	ret = FALSE;
	DWORD	attr, attr_mask = FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_READONLY;

	if (SHGetPathFromIDListV == NULL)	// NT4.0 系は無視
		return	FALSE;

	if ((attr = GetFileAttributesV(src)) == 0xffffffff || (attr & attr_mask) != attr_mask)
		return	FALSE;	// ディレクトリかつronly でないものは関係ない

	if (SUCCEEDED(CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
				  IID_IShellLinkV, (void **)&shellLink))) {
		if (SUCCEEDED(shellLink->QueryInterface(IID_IPersistFile, (void **)&persistFile))) {
			if (!IS_WINNT_V)
				AtoW((char *)src, wSrc, MAX_PATH);

			if (SUCCEEDED(persistFile->Load(wSrc, STGM_READ))) {
				if (SUCCEEDED(shellLink->GetPath((char *)wDst, MAX_PATH, 0, SLGP_UNCPRIORITY))) {
					if (!IS_WINNT_V)
						WtoA(wDst, (char *)wDstBuf, MAX_PATH);
					MakePathV(dst, wDstBuf, EMPTY_STR_V);
					ret = TRUE;
				}
			}
			persistFile->Release();
		}
		shellLink->Release();
	}

	return	ret;
}
예제 #9
0
void DoReport(LPCTSTR lpstrCmdLine, BOOL *pIsHandled)
{
	WSADATA wsaData = {0};
	WSAStartup(MAKEWORD(2, 2), &wsaData);

	//LogFinal(LOG::KBugReport) << L"Bugreport启动命令行: " << lpstrCmdLine;

	REPORT_CONTEXT report;
	std::wstring strProductName;

	const TCHAR * p = _tcsstr(lpstrCmdLine, _T("pid="));
	if (p)
	{
		*pIsHandled = TRUE;

		DWORD client_process_id = _tcstoul(p + _tcslen(_T("pid=")), 0, 0);

		p = _tcsstr(lpstrCmdLine, _T("context="));
		if (p)
		{
			void *addr = (void*)_tcstoul(p + _tcslen(_T("context=")), 0, 0);
			//YYBrowser Begin
			//by ZC. 2013-10-30 11:26.
			// hClientProcess客户进程,即是启动YGCrashReport的进程,不一定是崩溃的目标进程。
			HANDLE client_process_handle = ::OpenProcess(PROCESS_QUERY_INFORMATION|PROCESS_VM_READ, FALSE, client_process_id);
			// 崩溃目标进程。			
			HANDLE target_process_handle = NULL;
			//YYBrowser End
			if (!client_process_handle)
				LogFinal(LOG::KBugReport) << L"打开进程句柄失败";

			//解释REPORT_PARAMS
			CRASH_LAUNCH_PARAMS crash_launch_params = {0};
			DWORD cbRead = 0;
			if (addr && ::ReadProcessMemory(client_process_handle, addr, &crash_launch_params, sizeof(crash_launch_params), &cbRead))
			{
				LogFinal(LOG::KBugReport) << L"读取REPORT_PARAMS成功";
				
				std::set<std::wstring> setSuspectModule;
				std::set<std::wstring> setModule;
				std::wstring strPathNoExt = GenerateNewFilePath(crash_launch_params.dwPID);					

				report.strZipFilePath = strPathNoExt + _T(".zip");
				report.strOSVer = GetOSVer();

				AtoW(crash_launch_params.szProductName, -1, strProductName);
				
				report.dwReportId = crash_launch_params.dwReportId;
				report.strUserId = crash_launch_params.szUserId;
				report.strProductId = crash_launch_params.szProductId;
				report.strProductVer = crash_launch_params.szProductVer;
				report.strProductVerDetail = crash_launch_params.szProductVerDetail;
				//AtoW(crash_launch_params.szRestartExePath, -1, report.wstrRestartExePath);

				report.strDynaReleaseVer = crash_launch_params.szDynaReleaseVer;
			
				WriteBugInfo(report.dwReportId);
				report.dwCount24Hour = GetBugCount(report.dwReportId);

				//parse 自定义文件路径
				if (crash_launch_params.nFileCount > 0)
				{
					char *pPaths = new char[MAX_PATH * crash_launch_params.nFileCount];
					if (::ReadProcessMemory(client_process_handle, crash_launch_params.lpszCustomFilePaths, pPaths, MAX_PATH * crash_launch_params.nFileCount, &cbRead))
					{
						for (UINT k = 0; k < cbRead / MAX_PATH; k++)
						{
							std::wstring wstrPath;
							AtoW(pPaths + k * MAX_PATH, -1, wstrPath);
							report.vecOtherFilePath.push_back(wstrPath);
						}
					}
					delete [] pPaths;
					pPaths = NULL;
				}	
				
				//生成log
				std::string strLog;
				char szTemp[1024] = {0};


				//Date
				time_t curTime = 0;
				time(&curTime);
				strftime(szTemp, _countof(szTemp)-1, "%Y-%m-%d %H.%M.%S\r\n", localtime(&curTime));
				strLog += szTemp;
				strLog += "\r\n";

				//异常信息
				strLog += "Exception:\r\n";
				const char *pModName = strrchr(crash_launch_params.szExcepModPath, '\\');
				if (pModName)
					pModName++;
				else
					pModName = crash_launch_params.szExcepModPath;
			
				report.strExcepModuleName = pModName;
				_snprintf_s(szTemp, _countof(szTemp), _TRUNCATE, "Module=%s\r\n", pModName);
				strLog += szTemp;

				//YYBrowser Begin
				//打开目标进程。by ZC. 2013-10-30 11:30.
				target_process_handle = ::OpenProcess(PROCESS_QUERY_INFORMATION|PROCESS_VM_READ, FALSE, crash_launch_params.dwPID);
				//YYBrowser End
				//YYBrowser Begin
				//从目标进程中读出结构异常。by ZC. 2013-10-30 11:28.
				if (crash_launch_params.pExceptionInfo) {
					EXCEPTION_RECORD excep = {0};
					CONTEXT ct = {0};
					EXCEPTION_POINTERS ptr = {0};
					if (::ReadProcessMemory(target_process_handle, crash_launch_params.pExceptionInfo, &ptr, sizeof(ptr), &cbRead)
						&& ::ReadProcessMemory(target_process_handle, ptr.ExceptionRecord, &excep, sizeof(excep), &cbRead)
						&& ::ReadProcessMemory(target_process_handle, ptr.ContextRecord, &ct, sizeof(ct), &cbRead))
					{
						report.dwExcepAddr = (DWORD)excep.ExceptionAddress;
						report.dwExcepCode = excep.ExceptionCode;
						report.strExcepDiscription = GetExceptionDescription(excep.ExceptionCode);

						_snprintf_s(szTemp, _countof(szTemp), _TRUNCATE, "ExceptionCode=0x%08x, %s\r\n", excep.ExceptionCode, GetExceptionDescription(excep.ExceptionCode));
						strLog += szTemp;

						_snprintf_s(szTemp, _countof(szTemp), _TRUNCATE, "eip=0x%08x, ebp=0x%08x, esp=0x%08x, eax=0x%08x, ebx=0x%08x, ecx=0x%08x, edx=0x%08x, esi=0x%08x, edi=0x%08x\r\n", ct.Eip, ct.Ebp, ct.Esp, ct.Eax, ct.Ebx, ct.Ecx, ct.Edx, ct.Esi, ct.Edi);
						strLog += szTemp;
					}
					strLog += "\r\n";
				}
				//YYBrowser End

				strLog += "Summary:\r\n";
				strLog += GetSummary(client_process_handle);
				strLog += "UserId(YY)=" + report.strUserId + "\r\n";
				strLog += "ProductVer=" + report.strProductVer + "\r\n";
				strLog += "DynaReleaseVer=" + report.strDynaReleaseVer + "\r\n";				
				strLog += "ProductVerDetail=" + report.strProductVerDetail + "\r\n";
				_snprintf_s(szTemp, _countof(szTemp), _TRUNCATE, "ReportId=%u\r\n", report.dwReportId);
				strLog += szTemp;

				strLog += "\r\n";
				
				std::string strLoginHistoryLog;
				std::string strLoginHistory = ReadLoginHistory(strLoginHistoryLog);

				//用户自定义信息
				strLog += "CustomProperty:\r\n";
				char *pCustomProperty = new char[crash_launch_params.cchCustomProperty + 1];
				if (::ReadProcessMemory(client_process_handle, crash_launch_params.lpszCustomProperty, pCustomProperty, crash_launch_params.cchCustomProperty, &cbRead))
				{
					pCustomProperty[cbRead/sizeof(char)] = 0;

					report.strCustomProperty = pCustomProperty;
					
				}

				strLog += report.strCustomProperty;

				if(strLoginHistory.size()>0)
				{
					if(report.strCustomProperty.size()>0)
					{
						report.strCustomProperty+="&";
					}

					report.strCustomProperty+=strLoginHistory;
				}
			
				if(strLoginHistoryLog.size()>0)
				{
					strLog += "\r\n";
					strLog += strLoginHistoryLog;
				}
				strLog += "\r\n";

				//CallStack
				strLog += "Call Stack:\r\n";
				char *pCallStack = new char[crash_launch_params.cchCallStack + 1];
				cbRead = 0;
				if (::ReadProcessMemory(client_process_handle, crash_launch_params.lpszCallStack, pCallStack, crash_launch_params.cchCallStack, &cbRead))
				{
					pCallStack[cbRead/sizeof(char)] = 0;
					strLog += pCallStack;
				}
				strLog += "\r\n";

				//收集进程列表&检测运行环境
				std::string  strProcListA;
				std::wstring strProcListW;
				report.dwRunEnvironment = CheckRunEnvironment(strProcListW);
				WtoA(strProcListW.c_str(), -1, strProcListA);
				strLog += "Process List:\r\n";
				strLog += strProcListA;
				strLog += "\r\n";

				//收集版本的语言种类,不写入日志
				report.strProductLang = GetLanguageName();

				//模块列表
				strLog += "Module List:\r\n";
				strLog += GetModuleList(target_process_handle,&setModule,&setSuspectModule);
				strLog += "\r\n";
				
				//程序Log
				strLog += "Log:\r\n";
				TCHAR szExePath[MAX_PATH] = {0};
				GetModuleFileNameEx(target_process_handle, NULL, szExePath, _countof(szExePath));
				TCHAR *p = _tcsrchr(szExePath, _T('.'));
				if (p)
					*p = 0;
				TCHAR* pExeName = _tcsrchr(szExePath, _T('\\'));
				if (pExeName)
					pExeName++;
				else
					pExeName = szExePath;
				
				const DWORD dwMaxLogSize = 1024 * 200;
			//	char *pContent = new char [dwMaxLogSize];
			//	GetLastLog(pExeName, reportParams.dwPID, 0, pContent, dwMaxLogSize);
			//	strLog += pContent;
			//	delete [] pContent;
			//	pContent = NULL;
				strLog += "\r\n\r\n";
				/************************************************************************/
				/*功能:在日志文件中添加安装目录下所有dll和rcc文件的md5*/	
                /***************************只有yy.exe崩溃时,才会计算相关文件的md5*/
                if (StrCmpIA(crash_launch_params.szProductId, "YY") == 0)
                {
                    strLog += "[List *.dll and *.rcc files MD5:] \r\n\r\n";		
                    TCHAR szCurrentProcesspath[MAX_PATH] = {0};                
                    if ( GetModuleFileName(NULL,szCurrentProcesspath,_countof(szCurrentProcesspath)) > 0)
                    {
                        TCHAR* p_findDir = _tcsrchr(szCurrentProcesspath,_T('\\'));    
                        std::wstring rawCurrentProcessPath = szCurrentProcesspath;
                        std::wstring strCurrentProcesspath  =  rawCurrentProcessPath.substr(0, p_findDir - szCurrentProcesspath);

                        strLog += dwCalculateMD5(strCurrentProcesspath.c_str());                  
                    }
                    else
                    {
                        strLog += "Get the files'MD5 failed!";
                    }
                }
                else
                {
                    strLog += "Hint:\r\nThe crash was caused by the other products except the YY!";
                }				
                /************************************************************************/
				TCHAR szLogPath[_MAX_PATH] = {0};
				_sntprintf_s(szLogPath, _countof(szLogPath), _TRUNCATE, _T("%s.txt"), strPathNoExt.c_str());
				report.strLogPath = szLogPath;

				LogFinal(LOG::KBugReport) << L"写入log文件: " << szLogPath;
				
				HANDLE hFile = ::CreateFile(szLogPath, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, NULL, NULL);
				DWORD dwWriten = 0;
				::WriteFile(hFile, strLog.c_str(), strLog.size(), &dwWriten, NULL);
				::CloseHandle(hFile);
	
				//生成dump
				TCHAR szDumpPath[_MAX_PATH] = {0};
				_sntprintf_s(szDumpPath, _countof(szDumpPath), _TRUNCATE, _T("%s.dmp"), strPathNoExt.c_str());

				LogFinal(LOG::KBugReport) << L"生成dump文件: " << szDumpPath;
				int nDumpType = (MiniDumpNormal|MiniDumpWithHandleData|MiniDumpWithIndirectlyReferencedMemory|MiniDumpWithUnloadedModules|MiniDumpWithProcessThreadData);
				if (!CreateDump(szDumpPath, crash_launch_params.dwPID, crash_launch_params.dwTID, crash_launch_params.pExceptionInfo, nDumpType, MyMiniDumpCallBack, &crash_launch_params))
				{
					crash_launch_params.curCustomDataIdx = 0;
					CreateDump(szDumpPath, crash_launch_params.dwPID, crash_launch_params.dwTID, crash_launch_params.pExceptionInfo, MiniDumpNormal, MyMiniDumpCallBack, &crash_launch_params);
				}
				report.strDumpPath = szDumpPath;

				//生成fulldump
				CRegKey key;
				LONG lResult = key.Open(HKEY_CURRENT_USER, _T("Software\\duowan\\bugreport"), KEY_READ);
				if (ERROR_SUCCESS == lResult)
				{
					TCHAR	szFullDump[1024] = {0};
					DWORD dwSize = _countof(szFullDump);
					lResult = key.QueryValue(szFullDump, _T("fulldump"), &dwSize);
					if (ERROR_SUCCESS == lResult)
					{
						szFullDump[dwSize] = 0;
						if (_tcsicmp(szFullDump, _T("yes")) == 0)
						{
							nDumpType = (MiniDumpNormal 
								| MiniDumpWithFullMemory 
								| MiniDumpWithIndirectlyReferencedMemory 
								| MiniDumpWithHandleData
								| MiniDumpWithUnloadedModules
								| MiniDumpWithProcessThreadData);

							TCHAR szFullDumpPath[_MAX_PATH] = {0};
							::GetTempPath(_countof(szFullDumpPath), szFullDumpPath);
							_tcsncat_s(szFullDumpPath, _countof(szFullDumpPath), _T("duowan\\fulldump.dmp"), _TRUNCATE);

							LogFinal(LOG::KBugReport) << L"生成fulldump文件: " << szFullDumpPath;

							CreateDump(szFullDumpPath, crash_launch_params.dwPID, crash_launch_params.dwTID, crash_launch_params.pExceptionInfo, nDumpType, MyMiniDumpCallBack, &crash_launch_params);
						}
					}
				}

				::SetEvent(crash_launch_params.evDumpComplete);

				if (crash_launch_params.bShowReportUI)
				{
					LogFinal(LOG::KBugReport) << L"开始弹出崩溃界面";
					
					std::string strRecv;
					bool bShowModifyStatus = false;

					//if(GetBugModifyStatus(&report,strRecv))
					//{
					//	const char* p = strstr(strRecv.c_str(),"return=true");
					//	if(p)
					//	{
					//		bShowModifyStatus = true;
					//	}
					//}

					CMessageLoop theLoop;
					_Module.AddMessageLoop(&theLoop);

					CDlgReport dlgMain(strProductName.c_str(), &report, crash_launch_params.dwPID, &setModule, &setSuspectModule, bShowModifyStatus, strRecv.c_str());
					dlgMain.Create(NULL);

					dlgMain.ShowWindow(SW_SHOW);

					theLoop.Run();

					_Module.RemoveMessageLoop();
				}
				else
				{
					SendReport(&report, &setModule, &setSuspectModule);
				}
			}
			else
			{
				LogFinal(LOG::KBugReport) << L"读取崩溃进程REPORT_PARAMS失败";
			}

			::CloseHandle(target_process_handle);
			::CloseHandle(client_process_handle);
		}
	}
}
예제 #10
0
HRESULT MAPIContact::GetContactImage(wstring &wstrImagePath)
{
    HRESULT hr = S_OK;
    Zimbra::Util::ScopedInterface<IStream> pSrcStream;
    {
        Zimbra::Util::ScopedRowSet pAttachRows;
        Zimbra::Util::ScopedInterface<IMAPITable> pAttachTable;

        SizedSPropTagArray(3, attachProps) = {
            3, { PR_ATTACH_NUM, PR_ATTACH_SIZE, PR_ATTACH_LONG_FILENAME }
        };

        hr = m_pMessage->GetAttachmentTable(MAPI_UNICODE, pAttachTable.getptr());
        if (SUCCEEDED(hr))
        {
            if (FAILED(hr = pAttachTable->SetColumns((LPSPropTagArray) & attachProps, 0)))
                return hr;
            ULONG ulRowCount = 0;
            if (FAILED(hr = pAttachTable->GetRowCount(0, &ulRowCount)))
                return hr;
            if (FAILED(hr = pAttachTable->QueryRows(ulRowCount, 0, pAttachRows.getptr())))
                return hr;
            if (SUCCEEDED(hr))
            {
                hr = MAPI_E_NOT_FOUND;
                for (unsigned int i = 0; i < pAttachRows->cRows; i++)
                {
                    // if property couldn't be found or returns error, skip it
                    if ((pAttachRows->aRow[i].lpProps[2].ulPropTag == PT_ERROR) ||
                        (pAttachRows->aRow[i].lpProps[2].Value.err == MAPI_E_NOT_FOUND))
                        continue;
                    // Discard the attachmetnt if its not contact picture
                    if (_tcscmp(pAttachRows->aRow[i].lpProps[2].Value.LPSZ, _T(
                        "ContactPicture.jpg")))
                        continue;
                    Zimbra::Util::ScopedInterface<IAttach> pAttach;

                    if (FAILED(hr = m_pMessage->OpenAttach(
                            pAttachRows->aRow[i].lpProps[0].Value.l, NULL, 0,
                            pAttach.getptr())))
                        continue;
                    if (FAILED(hr = pAttach->OpenProperty(PR_ATTACH_DATA_BIN, &IID_IStream,
                            STGM_READ, 0, (LPUNKNOWN FAR *)pSrcStream.getptr())))
                        return hr;
                    break;
                }
            }
        }
    }

    if (hr != S_OK)
        return hr;

    // copy image to file
    wstring wstrTempAppDirPath;
    char *lpszDirName = NULL;
    char *lpszUniqueName = NULL;
    Zimbra::Util::ScopedInterface<IStream> pDestStream;

    if (!Zimbra::MAPI::Util::GetAppTemporaryDirectory(wstrTempAppDirPath))
        return MAPI_E_ACCESS_DENIED;
    WtoA((LPWSTR)wstrTempAppDirPath.c_str(), lpszDirName);

    string strFQFileName = lpszDirName;

    WtoA((LPWSTR)Zimbra::MAPI::Util::GetUniqueName().c_str(), lpszUniqueName);
    strFQFileName += "\\ZmContact_";
    strFQFileName += lpszUniqueName;
    strFQFileName += ".jpg";
    SafeDelete(lpszDirName);
    SafeDelete(lpszUniqueName);
    // Open stream on file
    if (FAILED(hr = OpenStreamOnFile(MAPIAllocateBuffer, MAPIFreeBuffer, STGM_CREATE |
            STGM_READWRITE, (LPTSTR)strFQFileName.c_str(), NULL, pDestStream.getptr())))
        return hr;
    ULARGE_INTEGER liAll = { 0 };
    liAll.QuadPart = (ULONGLONG)-1;
    if (FAILED(hr = pSrcStream->CopyTo(pDestStream.get(), liAll, NULL, NULL)))
        return hr;
    if (FAILED(hr = pDestStream->Commit(0)))
    {
        return hr;
        ;
    }

    // mime file path
    LPWSTR lpwstrFQFileName = NULL;

    AtoW((LPSTR)strFQFileName.c_str(), lpwstrFQFileName);
    wstrImagePath = lpwstrFQFileName;
    SafeDelete(lpwstrFQFileName);
    return hr;
}
예제 #11
0
HRESULT MAPIRfc2445::ExtractAttachments()
{
    // may need to break this up so we can call for exceptions, cancel exceptions

    LPCWSTR errMsg;
    Zimbra::Util::ScopedInterface<IStream> pIStream;
    UINT mimeLen = 0;
    HRESULT hr = ConvertIt( m_pMessage, pIStream.getptr(), mimeLen );
    if (FAILED(hr))
    {
        errMsg = FormatExceptionInfo(hr, L"Mime conversion of message with attachments failed", __FILE__, __LINE__);
        dlogw(errMsg);
        return hr;
    }

    mimepp::Message mimeMsg;
    Zimbra::Util::ScopedBuffer<CHAR> pszMimeMsg;

    // go to the beginning of the stream
    LARGE_INTEGER li = { 0 };

    hr = pIStream->Seek(li, STREAM_SEEK_SET, NULL);
    if (FAILED(hr))
    {
        errMsg = FormatExceptionInfo(hr, L"Stream seek failed", __FILE__, __LINE__);
        dlogw(errMsg);
        return hr;
    }

    // +1 for NULL terminator
    Zimbra::Mapi::Memory::AllocateBuffer(mimeLen + 1, (LPVOID *)pszMimeMsg.getptr());
    if (!pszMimeMsg.get())
    {
        errMsg = FormatExceptionInfo(S_OK, L"Mime msg Memory alloc failed", __FILE__, __LINE__);
        dlogw(errMsg);
        return hr;
    }

    ULONG ulNumRead = 0;

    hr = pIStream->Read((LPVOID)(pszMimeMsg.get()), mimeLen, &ulNumRead);
    if (FAILED(hr))
    {
        errMsg = FormatExceptionInfo(hr, L"Mime msg read failed", __FILE__, __LINE__);
        dlogw(errMsg);
        return hr;
    }
    if (ulNumRead != mimeLen)
    {
        errMsg = FormatExceptionInfo(hr, L"Mime msg read error", __FILE__, __LINE__);
        dlogw(errMsg);
        return hr;
    }

    // terminating string
    pszMimeMsg.get()[mimeLen] = '\0';

    mimeMsg.setString(pszMimeMsg.get());
    mimeMsg.parse();

    // let's see if this message is a multipart alternative before we continue
    mimepp::Headers &theHeaders = mimeMsg.headers();

    LPSTR pszContentType;
    GetContentType(theHeaders, &pszContentType);

    if(strncmp(pszContentType, "multipart/mixed", strlen("multipart/mixed")) != 0) 
    {
        // not what we are looking for
        delete[] pszContentType;
        return S_OK;
    }

    const mimepp::Body& theBody = mimeMsg.body();
    int numParts = theBody.numBodyParts();

    // FBS bug 73682 -- 5/23/12
    int numHiddenAttachments = GetNumHiddenAttachments();
    int totalAttachments = numParts - 1;
    if (totalAttachments == numHiddenAttachments)
    {
        return S_OK;
    }

    // let's look for a multipart mixed and grab the attachments
    int ctr = numHiddenAttachments;
    for(int i = 0; i < numParts; i++) 
    {
        // now look for attachments
        const mimepp::BodyPart& thePart = theBody.bodyPartAt(i);
        mimepp::DispositionType& disposition = thePart.headers().contentDisposition();
        if(disposition.asEnum() == mimepp::DispositionType::ATTACHMENT) 
        {
            const mimepp::String& theFilename = disposition.filename();

            LPSTR pszAttachContentType;
            LPSTR pszCD;
            LPSTR lpszRealName = new char[256];
            GetContentType(thePart.headers(), &pszAttachContentType);

            // FBS bug 73682 -- Exceptions are at the beginning.  Don't make attachments for those
            if (ctr > 0)
            {
                if (0 == strcmpi(pszAttachContentType, "message/rfc822"))
                {
                    ctr--;
                    continue;
                }
            }
            //

            if((LPSTR)theFilename.length()>0)
            {
                GenerateContentDisposition(&pszCD, (LPSTR)theFilename.c_str());
                strcpy(lpszRealName, (LPSTR)theFilename.c_str());
            }
            else
            {
                char cfilename[64];
                sprintf(cfilename,"attachment-%d",i);
                GenerateContentDisposition(&pszCD, cfilename);
                strcpy(lpszRealName, cfilename);
            }

            // now deal with the encoding
            LPSTR pContent = NULL;
            const mimepp::String &theContent = thePart.body().getString();
            mimepp::String outputString;
            UINT size = 0;

            mimepp::TransferEncodingType& transferEncoding = thePart.headers().contentTransferEncoding();

            if(transferEncoding.asEnum() == mimepp::TransferEncodingType::BASE64) 
            {
                // let's decode the buffer
                mimepp::Base64Decoder decoder;
                outputString = decoder.decode(theContent);
                pContent = (LPSTR)outputString.c_str();
                size = (UINT)outputString.size();
            } 
            else if(transferEncoding.asEnum() == mimepp::TransferEncodingType::QUOTED_PRINTABLE) 
            {
                mimepp::QuotedPrintableDecoder decoder;
                outputString  = decoder.decode(theContent);
                pContent = (LPSTR)outputString.c_str();
                size = (UINT)outputString.size();
            } 
            else 
            {
                pContent = (LPSTR)theContent.c_str();
                size = (UINT)theContent.size();
            }

	    // Save stream to temp file in temp dir.  We'll delete in ZimbraAPI //
            LPCWSTR errMsg;
            HRESULT hr = S_OK;

            wstring wstrTempAppDirPath;
            LPSTR lpszFQFileName = new char[256];
            LPSTR lpszDirName = NULL;
            LPSTR lpszUniqueName = NULL;
            Zimbra::Util::ScopedInterface<IStream> pStream;

            if (!Zimbra::MAPI::Util::GetAppTemporaryDirectory(wstrTempAppDirPath))
            {
                errMsg = FormatExceptionInfo(S_OK, L"GetAppTemporaryDirectory Failed", __FILE__, __LINE__);
                dloge("MAPIRfc2445 -- exception");
                dloge(errMsg);
                return E_FAIL;
            }
            WtoA((LPWSTR)wstrTempAppDirPath.c_str(), lpszDirName);
            WtoA((LPWSTR)Zimbra::MAPI::Util::GetUniqueName().c_str(), lpszUniqueName);
            strcpy(lpszFQFileName, lpszDirName);
            strcat(lpszFQFileName, "\\");
            strcat(lpszFQFileName, lpszUniqueName);

            SafeDelete(lpszDirName);
            SafeDelete(lpszUniqueName);

            // Open stream on file
            if (FAILED(hr = OpenStreamOnFile(MAPIAllocateBuffer, MAPIFreeBuffer, STGM_CREATE |
                    STGM_READWRITE, (LPTSTR)lpszFQFileName, NULL, pStream.getptr())))
            {
                errMsg = FormatExceptionInfo(hr, L"Error: OpenStreamOnFile Failed.", __FILE__, __LINE__);
                dloge("MAPIRfc2445 -- exception");
                dloge(errMsg);
                return hr;
            }

            ULONG nBytesToWrite = size;
            ULONG nBytesWritten = 0;
            LPBYTE pCur = (LPBYTE)pContent;
            while (!FAILED(hr) && nBytesToWrite > 0) 
            {
                hr = pStream->Write(pCur, nBytesToWrite, &nBytesWritten);
                pCur += nBytesWritten;
                nBytesToWrite -= nBytesWritten;
            }
            if (FAILED(hr = pStream->Commit(0)))
            {
                errMsg = FormatExceptionInfo(hr, L"Error: Stream Write Failed.", __FILE__, __LINE__);
                dloge("MAPIRfc2445 -- exception");
                dloge(errMsg);
            }
            ///////////

            // delete all this in MAPIAccessWrap
            AttachmentInfo* pAttachmentInfo = new AttachmentInfo();
            pAttachmentInfo->pszTempFile = lpszFQFileName;
            pAttachmentInfo->pszRealName = lpszRealName;
            pAttachmentInfo->pszContentDisposition = pszCD;
            pAttachmentInfo->pszContentType = pszAttachContentType;
            m_vAttachments.push_back(pAttachmentInfo);
        }
    }
    delete[] pszContentType;
    return S_OK;
}
예제 #12
0
HRESULT create_monodata(REFIID riid, LPVOID *ppObj )
{
    static const WCHAR wszCodebase[] = {'C','o','d','e','B','a','s','e',0};
    static const WCHAR wszClass[] = {'C','l','a','s','s',0};
    static const WCHAR wszFileSlash[] = {'f','i','l','e',':','/','/','/',0};
    static const WCHAR wszCLSIDSlash[] = {'C','L','S','I','D','\\',0};
    static const WCHAR wszInprocServer32[] = {'\\','I','n','p','r','o','c','S','e','r','v','e','r','3','2',0};
    WCHAR path[CHARS_IN_GUID + ARRAYSIZE(wszCLSIDSlash) + ARRAYSIZE(wszInprocServer32) - 1];
    MonoDomain *domain;
    MonoAssembly *assembly;
    ICLRRuntimeInfo *info;
    RuntimeHost *host;
    HRESULT hr;
    HKEY key;
    LONG res;
    int offset = 0;
    WCHAR codebase[MAX_PATH + 8];
    WCHAR classname[350];
    WCHAR filename[MAX_PATH];

    DWORD dwBufLen = 350;

    lstrcpyW(path, wszCLSIDSlash);
    StringFromGUID2(riid, path + lstrlenW(wszCLSIDSlash), CHARS_IN_GUID);
    lstrcatW(path, wszInprocServer32);

    TRACE("Registry key: %s\n", debugstr_w(path));

    res = RegOpenKeyExW(HKEY_CLASSES_ROOT, path, 0, KEY_READ, &key);
    if (res == ERROR_FILE_NOT_FOUND)
        return CLASS_E_CLASSNOTAVAILABLE;

    res = RegGetValueW( key, NULL, wszClass, RRF_RT_REG_SZ, NULL, classname, &dwBufLen);
    if(res != ERROR_SUCCESS)
    {
        WARN("Class value cannot be found.\n");
        hr = CLASS_E_CLASSNOTAVAILABLE;
        goto cleanup;
    }

    TRACE("classname (%s)\n", debugstr_w(classname));

    dwBufLen = MAX_PATH + 8;
    res = RegGetValueW( key, NULL, wszCodebase, RRF_RT_REG_SZ, NULL, codebase, &dwBufLen);
    if(res != ERROR_SUCCESS)
    {
        WARN("CodeBase value cannot be found.\n");
        hr = CLASS_E_CLASSNOTAVAILABLE;
        goto cleanup;
    }

    /* Strip file:/// */
    if(strncmpW(codebase, wszFileSlash, strlenW(wszFileSlash)) == 0)
        offset = strlenW(wszFileSlash);

    strcpyW(filename, codebase + offset);

    TRACE("codebase (%s)\n", debugstr_w(filename));

    *ppObj = NULL;


    hr = get_runtime_info(filename, NULL, NULL, 0, 0, FALSE, &info);
    if (SUCCEEDED(hr))
    {
        hr = ICLRRuntimeInfo_GetRuntimeHost(info, &host);

        if (SUCCEEDED(hr))
            hr = RuntimeHost_GetDefaultDomain(host, &domain);

        if (SUCCEEDED(hr))
        {
            MonoImage *image;
            MonoClass *klass;
            MonoObject *result;
            IUnknown *unk = NULL;
            char *filenameA, *ns;
            char *classA;

            hr = CLASS_E_CLASSNOTAVAILABLE;

            host->mono->mono_thread_attach(domain);

            filenameA = WtoA(filename);
            assembly = host->mono->mono_domain_assembly_open(domain, filenameA);
            HeapFree(GetProcessHeap(), 0, filenameA);
            if (!assembly)
            {
                ERR("Cannot open assembly %s\n", filenameA);
                goto cleanup;
            }

            image = host->mono->mono_assembly_get_image(assembly);
            if (!image)
            {
                ERR("Couldn't get assembly image\n");
                goto cleanup;
            }

            classA = WtoA(classname);
            ns = strrchr(classA, '.');
            *ns = '\0';

            klass = host->mono->mono_class_from_name(image, classA, ns+1);
            HeapFree(GetProcessHeap(), 0, classA);
            if (!klass)
            {
                ERR("Couldn't get class from image\n");
                goto cleanup;
            }

            /*
             * Use the default constructor for the .NET class.
             */
            result = host->mono->mono_object_new(domain, klass);
            host->mono->mono_runtime_object_init(result);

            hr = RuntimeHost_GetIUnknownForObject(host, result, &unk);
            if (SUCCEEDED(hr))
            {
                hr = IUnknown_QueryInterface(unk, &IID_IUnknown, ppObj);

                IUnknown_Release(unk);
            }
            else
                hr = CLASS_E_CLASSNOTAVAILABLE;
        }
        else
            hr = CLASS_E_CLASSNOTAVAILABLE;
    }
    else
        hr = CLASS_E_CLASSNOTAVAILABLE;

cleanup:
    if(info)
        ICLRRuntimeInfo_Release(info);

    RegCloseKey(key);

    return hr;
}
예제 #13
0
BOOL CParseChText4::SaveChText(LPCWSTR filePath)
{
	wstring loadFilePath = L"";
	if( filePath == NULL ){
		loadFilePath = this->filePath;
	}else{
		loadFilePath = filePath;
	}

	if( loadFilePath.size() == 0 ){
		return FALSE;
	}

/*
	std::wregex re(L".+\\(.+)\(.+\)\.ChSet4\.txt$");
	
	
	std::wstring text(str);
	std::wsmatch m;

	if( std::regex_search(text, m, re) ) this->mpStartTimeShifting = m[1];
*/



	HANDLE hFile = _CreateFile2( loadFilePath.c_str(), GENERIC_WRITE, FILE_SHARE_READ, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
	if( hFile == INVALID_HANDLE_VALUE ){
		return FALSE;
	}

	multimap<LONGLONG, CH_DATA4> sortList;
	multimap<LONGLONG, CH_DATA4>::iterator itr;
	for( itr = this->chList.begin(); itr != this->chList.end(); itr++ ){
		LONGLONG Key = ((LONGLONG)itr->second.space)<<32 | ((LONGLONG)itr->second.ch)<<16 | (LONGLONG)itr->second.serviceID;
		sortList.insert(pair<LONGLONG, CH_DATA4>(Key, itr->second));
	}

	for( itr = sortList.begin(); itr != sortList.end(); itr++ ){
		string chName="";
		WtoA(itr->second.chName, chName);
		string serviceName="";
		WtoA(itr->second.serviceName, serviceName);
		string networkName="";
		WtoA(itr->second.networkName, networkName);

		string strBuff;
		Format(strBuff, "%s\t%s\t%s\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\r\n",
			chName.c_str(),
			serviceName.c_str(),
			networkName.c_str(),
			itr->second.space,
			itr->second.ch,
			itr->second.originalNetworkID,
			itr->second.transportStreamID,
			itr->second.serviceID,
			itr->second.serviceType,
			itr->second.partialFlag,
			itr->second.useViewFlag,
			itr->second.remoconID
			);
		DWORD dwWrite = 0;
		WriteFile(hFile, strBuff.c_str(), (DWORD)strBuff.length(), &dwWrite, NULL);
	}

	CloseHandle(hFile);
	return TRUE;
}
예제 #14
0
BOOL CSyoboiCalUtil::SendReserve(const vector<RESERVE_DATA>* reserveList, const vector<TUNER_RESERVE_INFO>* tunerList)
{
	if( reserveList == NULL || tunerList == NULL ){
		return FALSE;
	}
	if( reserveList->size() == 0 ){
		return FALSE;
	}

	wstring iniAppPath = L"";
	GetModuleIniPath(iniAppPath);
	if( GetPrivateProfileInt(L"SYOBOI", L"use", 0, iniAppPath.c_str()) == 0 ){
		return FALSE;
	}
	_OutputDebugString(L"★SyoboiCalUtil:SendReserve");

	wstring textPath;
	GetModuleFolderPath(textPath);
	textPath += L"\\SyoboiCh.txt";
	CParseServiceChgText srvChg;
	srvChg.ParseText(textPath.c_str());

	wstring proxyServerName;
	wstring proxyUserName;
	wstring proxyPassword;
	if( GetPrivateProfileInt(L"SYOBOI", L"useProxy", 0, iniAppPath.c_str()) != 0 ){
		proxyServerName = GetPrivateProfileToString(L"SYOBOI", L"ProxyServer", L"", iniAppPath.c_str());
		proxyUserName = GetPrivateProfileToString(L"SYOBOI", L"ProxyID", L"", iniAppPath.c_str());
		proxyPassword = GetPrivateProfileToString(L"SYOBOI", L"ProxyPWD", L"", iniAppPath.c_str());
	}

	wstring id=GetPrivateProfileToString(L"SYOBOI", L"userID", L"", iniAppPath.c_str());

	wstring pass=GetPrivateProfileToString(L"SYOBOI", L"PWD", L"", iniAppPath.c_str());

	int slot = GetPrivateProfileInt(L"SYOBOI", L"slot", 0, iniAppPath.c_str());

	wstring devcolors=GetPrivateProfileToString(L"SYOBOI", L"devcolors", L"", iniAppPath.c_str());
	
	wstring epgurl=GetPrivateProfileToString(L"SYOBOI", L"epgurl", L"", iniAppPath.c_str());

	if( id.size() == 0 ){
		_OutputDebugString(L"★SyoboiCalUtil:NoUserID");
		return FALSE;
	}

	//Authorization
	wstring auth = L"";
	auth = id;
	auth += L":";
	auth += pass;
	string authA;
	WtoA(auth, authA);

	DWORD destSize = 0;
	Base64Enc(authA.c_str(), (DWORD)authA.size(), NULL, &destSize);
	vector<WCHAR> base64(destSize + 1, L'\0');
	Base64Enc(authA.c_str(), (DWORD)authA.size(), &base64.front(), &destSize);
	//無駄なCRLFが混じることがあるため
	std::replace(base64.begin(), base64.end(), L'\r', L'\0');
	std::replace(base64.begin(), base64.end(), L'\n', L'\0');

	wstring authHead = L"";
	Format(authHead, L"Authorization: Basic %s\r\nContent-type: application/x-www-form-urlencoded\r\n", &base64.front());

	//data
	wstring dataParam;
	wstring param;
	map<DWORD, wstring> tunerMap;
	for( size_t i=0; i<tunerList->size(); i++ ){
		for( size_t j=0; j<(*tunerList)[i].reserveList.size(); j++ ){
			tunerMap.insert(pair<DWORD, wstring>((*tunerList)[i].reserveList[j], (*tunerList)[i].tunerName));
		}
	}
	map<DWORD, wstring>::iterator itrTuner;
	DWORD dataCount = 0;
	for(size_t i=0; i<reserveList->size(); i++ ){
		if( dataCount>=200 ){
			break;
		}
		const RESERVE_DATA* info = &(*reserveList)[i];
		if( info->recSetting.recMode == RECMODE_NO || info->recSetting.recMode == RECMODE_VIEW ){
			continue;
		}
		wstring device=L"";
		itrTuner = tunerMap.find(info->reserveID);
		if( itrTuner != tunerMap.end() ){
			device = itrTuner->second;
		}

		wstring stationName = info->stationName;
		srvChg.ChgText(stationName);

		__int64 startTime = GetTimeStamp(info->startTime);
		Format(param, L"%I64d\t%I64d\t%s\t%s\t%s\t\t0\t%d\n", startTime, startTime+info->durationSecond, device.c_str(), info->title.c_str(), stationName.c_str(), info->reserveID );
		dataParam+=param;
	}

	if(dataParam.size() == 0 ){
		_OutputDebugString(L"★SyoboiCalUtil:NoReserve");
		return FALSE;
	}

	string utf8;
	UrlEncodeUTF8(dataParam.c_str(), (DWORD)dataParam.size(), utf8);
	string data;
	Format(data, "slot=%d&data=%s",slot, utf8.c_str());

	if( devcolors.size() > 0){
		utf8 = "";
		UrlEncodeUTF8(devcolors.c_str(), (DWORD)devcolors.size(), utf8);
		data += "&devcolors=";
		data += utf8;
	}
	if( epgurl.size() > 0){
		utf8 = "";
		UrlEncodeUTF8(epgurl.c_str(), (DWORD)epgurl.size(), utf8);
		data += "&epgurl=";
		data += utf8;
	}
	vector<char> dataBuff(data.begin(), data.end());

	//URLの分解
	URL_COMPONENTS stURL = {};
	stURL.dwStructSize = sizeof(stURL);
	stURL.dwSchemeLength = (DWORD)-1;
	stURL.dwHostNameLength = (DWORD)-1;
	stURL.dwUrlPathLength = (DWORD)-1;
	stURL.dwExtraInfoLength = (DWORD)-1;
	if( WinHttpCrackUrl(SYOBOI_UP_URL, 0, 0, &stURL) == FALSE || stURL.dwHostNameLength == 0 ){
		return FALSE;
	}
	wstring host(stURL.lpszHostName, stURL.dwHostNameLength);
	wstring sendUrl(stURL.lpszUrlPath, stURL.dwUrlPathLength + stURL.dwExtraInfoLength);

	HINTERNET session;
	if( proxyServerName.empty() ){
		session = WinHttpOpen(L"EpgTimerSrv", WINHTTP_ACCESS_TYPE_NO_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
	}else{
		session = WinHttpOpen(L"EpgTimerSrv", WINHTTP_ACCESS_TYPE_NAMED_PROXY, proxyServerName.c_str(), WINHTTP_NO_PROXY_BYPASS, 0);
	}
	if( session == NULL ){
		return FALSE;
	}

	LPCWSTR result = L"1";
	HINTERNET connect = NULL;
	HINTERNET request = NULL;

	if( WinHttpSetTimeouts(session, 15000, 15000, 15000, 15000) == FALSE ){
		result = L"0 SetTimeouts";
		goto EXIT;
	}
	//コネクションオープン
	connect = WinHttpConnect(session, host.c_str(), stURL.nPort, 0);
	if( connect == NULL ){
		result = L"0 Connect";
		goto EXIT;
	}
	//リクエストオープン
	request = WinHttpOpenRequest(connect, L"POST", sendUrl.c_str(), NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES,
	                             stURL.nPort == INTERNET_DEFAULT_HTTPS_PORT ? WINHTTP_FLAG_SECURE : 0);
	if( request == NULL ){
		result = L"0 OpenRequest";
		goto EXIT;
	}
	if( proxyServerName.empty() == false ){
		//ProxyのIDかパスワードがあったらセット
		if( proxyUserName.empty() == false || proxyPassword.empty() == false ){
			if( WinHttpSetCredentials(request, WINHTTP_AUTH_TARGET_PROXY, WINHTTP_AUTH_SCHEME_BASIC,
			                          proxyUserName.c_str(), proxyPassword.c_str(), NULL) == FALSE ){
				result = L"0 SetCredentials";
				goto EXIT;
			}
		}
	}
	if( WinHttpSendRequest(request, authHead.c_str(), (DWORD)-1, &dataBuff.front(), (DWORD)dataBuff.size(), (DWORD)dataBuff.size(), 0) == FALSE ){
		result = L"0 SendRequest";
		goto EXIT;
	}
	if( WinHttpReceiveResponse(request, NULL) == FALSE ){
		result = L"0 ReceiveResponse";
		goto EXIT;
	}
	//HTTPのステータスコード確認
	DWORD statusCode;
	DWORD statusCodeSize = sizeof(statusCode);
	if( WinHttpQueryHeaders(request, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, WINHTTP_HEADER_NAME_BY_INDEX,
	                        &statusCode, &statusCodeSize, WINHTTP_NO_HEADER_INDEX) == FALSE ){
		statusCode = 0;
	}
	if( statusCode != 200 && statusCode != 201 ){
		result = L"0 StatusNotOK";
		goto EXIT;
	}

EXIT:
	if( request != NULL ){
		WinHttpCloseHandle(request);
	}
	if( connect != NULL ){
		WinHttpCloseHandle(connect);
	}
	if( session != NULL ){
		WinHttpCloseHandle(session);
	}

	_OutputDebugString(L"★SyoboiCalUtil:SendRequest res:%s", result);

	if( result[0] != L'1' ){
		return FALSE;
	}
	return TRUE;
}
예제 #15
0
int CHttpPublicFileSend::HttpRequest(string method, string uri, nocase::map<string, string>* headerList, SOCKET clientSock, HANDLE stopEvent)
{
	int ret = 200;
	string buff = "";
	string path = "";
	string rootA = "";
	wstring filePath = L"";
	wstring wbuff = L"";
	map<string, wstring>::iterator itrVPath;
	nocase::map<string, string>::iterator itrHead;
	nocase::map<string, string> httpResHeader;
	__int64 fileSize = 0;
	string contentType = "";
	__int64 offset = 0;
	__int64 endPos = 0;
	map<__int64, __int64> rangeList;

	if( this->folderPath.size() == 0 || this->rootUri.size() == 0){
		ret = 404;
		goto Err_End;
	}
	if( CompareNoCase(method, "GET") != 0 ){
		ret = 404;
		goto Err_End;
	}

	WtoA(this->rootUri, rootA);

	UrlDecode(uri.c_str(), (DWORD)uri.size(), buff);


	//仮想パスから検索
	for(itrVPath = this->virtualPathList.begin(); itrVPath != this->virtualPathList.end(); itrVPath++){
		string key;
		Format(key, "%s/%s/", rootA.c_str(), itrVPath->first.c_str());

		if( buff.find(key) == 0 ){
			Separate(buff, key, buff, path);
			Replace(path, "/", "\\");

			UTF8toW(path, wbuff);

			filePath = itrVPath->second;
			ChkFolderPath(filePath);
			filePath += L"\\";
			filePath += wbuff;
			break;
		}
	}

	if(filePath.size() == 0 ){
		//通常のルート
		Separate(buff, rootA, buff, path);
		Replace(path, "/", "\\");

		UTF8toW(path, wbuff);

		filePath = this->folderPath;
		ChkFolderPath(filePath);
		filePath += L"\\";
		filePath += wbuff;
	}

	if( PathFileExists(filePath.c_str()) == FALSE ){
		ret = 404;
		goto Err_End;
	}

	httpSend.GetContentType(filePath, contentType);
	fileSize = httpSend.GetContentLength(filePath);

	endPos = fileSize;

	itrHead = headerList->find("Range");
	if( itrHead == headerList->end() ){
		//Rangeなし
		Format(buff, "%I64d", fileSize);
		httpResHeader.insert(pair<string, string>("Content-Length", buff));
		httpResHeader.insert(pair<string, string>("Content-Type", contentType));

		httpSend.SendResponseHeader(200, &httpResHeader, clientSock, stopEvent);
		httpSend.SendFile(filePath, offset, endPos, clientSock, stopEvent);
	}else{
		if( httpSend.ParseRangeHeader(fileSize, itrHead->second, &rangeList) == FALSE ){
			//Range指定が何かおかしい
			Format(buff, "%I64d", fileSize);
			httpResHeader.insert(pair<string, string>("Content-Length", buff));
			httpResHeader.insert(pair<string, string>("Content-Type", contentType));

			httpSend.SendResponseHeader(200, &httpResHeader, clientSock, stopEvent);
			httpSend.SendFile(filePath, offset, endPos, clientSock, stopEvent);
		}else{
			httpResHeader.insert(pair<string, string>("Accept-Ranges", "bytes"));
			if( rangeList.size() > 1 ){
				//複数の場所指定
				Format(buff, "multipart/byteranges; boundary=%s", MULTI_PART_BOUNDARY);
				httpResHeader.insert(pair<string, string>("Content-Type", buff));

				httpSend.SendResponseHeader(206, &httpResHeader, clientSock, stopEvent);


				map<__int64, __int64>::iterator itr;
				string boundary = "";
				for( itr = rangeList.begin(); itr != rangeList.end(); itr++ ){
					boundary = "--";
					boundary += MULTI_PART_BOUNDARY;
					boundary += "\r\n";
					Format(buff, "Content-Type: %s\r\n", contentType);
					boundary += buff;
					Format(buff, "Content-Range: bytes %I64d-%I64d/%I64d\r\n", itr->first, itr->second, fileSize);
					boundary += buff;
					boundary += "\r\n";

					if( httpSend.SendData((BYTE*)boundary.c_str(), (DWORD)boundary.size(), clientSock, stopEvent) != NO_ERR ){
						goto End;
					}
					if( httpSend.SendFile(filePath, itr->first, itr->second+1, clientSock, stopEvent) != NO_ERR ){
						goto End;
					}

					boundary = "\r\n";
					httpSend.SendData((BYTE*)boundary.c_str(), (DWORD)boundary.size(), clientSock, stopEvent);
				}
				boundary = "--";
				boundary += MULTI_PART_BOUNDARY;
				boundary += "--\r\n";
				httpSend.SendData((BYTE*)boundary.c_str(), (DWORD)boundary.size(), clientSock, stopEvent);
			}else{
				//一カ所のみ
				map<__int64, __int64>::iterator itr;
				itr = rangeList.begin();

				httpResHeader.insert(pair<string, string>("Content-Type", contentType));
				Format(buff, "bytes %I64d-%I64d/%I64d", itr->first, itr->second, fileSize);
				httpResHeader.insert(pair<string, string>("Content-Range", buff));
				Format(buff, "%I64d", itr->second-itr->first+1);
				httpResHeader.insert(pair<string, string>("Content-Length", buff));

				httpSend.SendResponseHeader(206, &httpResHeader, clientSock, stopEvent);
				httpSend.SendFile(filePath, itr->first, itr->second+1, clientSock, stopEvent);

			}
		}
	}



	return ret;

Err_End:
	httpSend.SendResponseHeader(ret, &httpResHeader, clientSock, stopEvent);
End:
	return ret;
}
예제 #16
0
void *toV(const WCHAR *src, BOOL noStatic) {
	if (!IS_WINNT_V) {
		return	WtoA(src, noStatic);
	}
	return	noStatic ? wcsdupNew(src) : (void *)src;
}
예제 #17
0
static void CDECL ReallyFixupVTable(struct dll_fixup *fixup)
{
    HRESULT hr=S_OK;
    WCHAR filename[MAX_PATH];
    ICLRRuntimeInfo *info=NULL;
    RuntimeHost *host;
    char *filenameA;
    MonoImage *image=NULL;
    MonoAssembly *assembly=NULL;
    MonoImageOpenStatus status=0;
    MonoDomain *domain;

    if (fixup->done) return;

    /* It's possible we'll have two threads doing this at once. This is
     * considered preferable to the potential deadlock if we use a mutex. */

    GetModuleFileNameW(fixup->dll, filename, MAX_PATH);

    TRACE("%p,%p,%s\n", fixup, fixup->dll, debugstr_w(filename));

    filenameA = WtoA(filename);
    if (!filenameA)
        hr = E_OUTOFMEMORY;

    if (SUCCEEDED(hr))
        hr = get_runtime_info(filename, NULL, NULL, 0, 0, FALSE, &info);

    if (SUCCEEDED(hr))
        hr = ICLRRuntimeInfo_GetRuntimeHost(info, &host);

    if (SUCCEEDED(hr))
        hr = RuntimeHost_GetDefaultDomain(host, &domain);

    if (SUCCEEDED(hr))
    {
        mono_thread_attach(domain);

        assembly = mono_assembly_open(filenameA, &status);
    }

    if (assembly)
    {
        int i;

        /* Mono needs an image that belongs to an assembly. */
        image = mono_assembly_get_image(assembly);

        if (fixup->fixup->type & COR_VTABLE_32BIT)
        {
            DWORD *vtable = fixup->vtable;
            DWORD *tokens = fixup->tokens;
            for (i=0; i<fixup->fixup->count; i++)
            {
                TRACE("%x\n", tokens[i]);
                vtable[i] = PtrToUint(mono_marshal_get_vtfixup_ftnptr(
                    image, tokens[i], fixup->fixup->type));
            }
        }

        fixup->done = TRUE;
    }

    if (info != NULL)
        ICLRRuntimeInfo_Release(info);

    HeapFree(GetProcessHeap(), 0, filenameA);

    if (!fixup->done)
    {
        ERR("unable to fixup vtable, hr=%x, status=%d\n", hr, status);
        /* If we returned now, we'd get an infinite loop. */
        assert(0);
    }
}
예제 #18
0
HRESULT create_monodata(REFIID riid, LPVOID *ppObj )
{
    static const WCHAR wszAssembly[] = {'A','s','s','e','m','b','l','y',0};
    static const WCHAR wszCodebase[] = {'C','o','d','e','B','a','s','e',0};
    static const WCHAR wszClass[] = {'C','l','a','s','s',0};
    static const WCHAR wszFileSlash[] = {'f','i','l','e',':','/','/','/',0};
    static const WCHAR wszCLSIDSlash[] = {'C','L','S','I','D','\\',0};
    static const WCHAR wszInprocServer32[] = {'\\','I','n','p','r','o','c','S','e','r','v','e','r','3','2',0};
    static const WCHAR wszDLL[] = {'.','d','l','l',0};
    WCHAR path[CHARS_IN_GUID + ARRAYSIZE(wszCLSIDSlash) + ARRAYSIZE(wszInprocServer32) - 1];
    MonoDomain *domain;
    MonoAssembly *assembly;
    ICLRRuntimeInfo *info = NULL;
    RuntimeHost *host;
    HRESULT hr;
    HKEY key, subkey;
    LONG res;
    int offset = 0;
    DWORD numKeys, keyLength;
    WCHAR codebase[MAX_PATH + 8];
    WCHAR classname[350], subkeyName[256];
    WCHAR filename[MAX_PATH];

    DWORD dwBufLen = 350;

    lstrcpyW(path, wszCLSIDSlash);
    StringFromGUID2(riid, path + lstrlenW(wszCLSIDSlash), CHARS_IN_GUID);
    lstrcatW(path, wszInprocServer32);

    TRACE("Registry key: %s\n", debugstr_w(path));

    res = RegOpenKeyExW(HKEY_CLASSES_ROOT, path, 0, KEY_READ, &key);
    if (res == ERROR_FILE_NOT_FOUND)
        return CLASS_E_CLASSNOTAVAILABLE;

    res = RegGetValueW( key, NULL, wszClass, RRF_RT_REG_SZ, NULL, classname, &dwBufLen);
    if(res != ERROR_SUCCESS)
    {
        WARN("Class value cannot be found.\n");
        hr = CLASS_E_CLASSNOTAVAILABLE;
        goto cleanup;
    }

    TRACE("classname (%s)\n", debugstr_w(classname));

    dwBufLen = MAX_PATH + 8;
    res = RegGetValueW( key, NULL, wszCodebase, RRF_RT_REG_SZ, NULL, codebase, &dwBufLen);
    if(res == ERROR_SUCCESS)
    {
        /* Strip file:/// */
        if(strncmpW(codebase, wszFileSlash, strlenW(wszFileSlash)) == 0)
            offset = strlenW(wszFileSlash);

        strcpyW(filename, codebase + offset);
    }
    else
    {
        WCHAR assemblyname[MAX_PATH + 8];

        hr = CLASS_E_CLASSNOTAVAILABLE;
        WARN("CodeBase value cannot be found, trying Assembly.\n");
        /* get the last subkey of InprocServer32 */
        res = RegQueryInfoKeyW(key, 0, 0, 0, &numKeys, 0, 0, 0, 0, 0, 0, 0);
        if (res != ERROR_SUCCESS || numKeys == 0)
            goto cleanup;
        numKeys--;
        keyLength = sizeof(subkeyName) / sizeof(WCHAR);
        res = RegEnumKeyExW(key, numKeys, subkeyName, &keyLength, 0, 0, 0, 0);
        if (res != ERROR_SUCCESS)
            goto cleanup;
        res = RegOpenKeyExW(key, subkeyName, 0, KEY_READ, &subkey);
        if (res != ERROR_SUCCESS)
            goto cleanup;
        dwBufLen = MAX_PATH + 8;
        res = RegGetValueW(subkey, NULL, wszAssembly, RRF_RT_REG_SZ, NULL, assemblyname, &dwBufLen);
        RegCloseKey(subkey);
        if (res != ERROR_SUCCESS)
            goto cleanup;

        hr = get_file_from_strongname(assemblyname, filename, MAX_PATH);
        if (!SUCCEEDED(hr))
        {
            /*
             * The registry doesn't have a CodeBase entry and it's not in the GAC.
             *
             * Use the Assembly Key to retrieve the filename.
             *    Assembly : REG_SZ : AssemblyName, Version=X.X.X.X, Culture=neutral, PublicKeyToken=null
             */
            WCHAR *ns;

            WARN("Attempt to load from the application directory.\n");
            GetModuleFileNameW(NULL, filename, MAX_PATH);
            ns = strrchrW(filename, '\\');
            *(ns+1) = '\0';

            ns = strchrW(assemblyname, ',');
            *(ns) = '\0';
            strcatW(filename, assemblyname);
            *(ns) = '.';
            strcatW(filename, wszDLL);
        }
    }

    TRACE("filename (%s)\n", debugstr_w(filename));

    *ppObj = NULL;


    hr = get_runtime_info(filename, NULL, NULL, 0, 0, FALSE, &info);
    if (SUCCEEDED(hr))
    {
        hr = ICLRRuntimeInfo_GetRuntimeHost(info, &host);

        if (SUCCEEDED(hr))
            hr = RuntimeHost_GetDefaultDomain(host, &domain);

        if (SUCCEEDED(hr))
        {
            MonoImage *image;
            MonoClass *klass;
            MonoObject *result;
            IUnknown *unk = NULL;
            char *filenameA, *ns;
            char *classA;

            hr = CLASS_E_CLASSNOTAVAILABLE;

            mono_thread_attach(domain);

            filenameA = WtoA(filename);
            assembly = mono_domain_assembly_open(domain, filenameA);
            HeapFree(GetProcessHeap(), 0, filenameA);
            if (!assembly)
            {
                ERR("Cannot open assembly %s\n", filenameA);
                goto cleanup;
            }

            image = mono_assembly_get_image(assembly);
            if (!image)
            {
                ERR("Couldn't get assembly image\n");
                goto cleanup;
            }

            classA = WtoA(classname);
            ns = strrchr(classA, '.');
            *ns = '\0';

            klass = mono_class_from_name(image, classA, ns+1);
            HeapFree(GetProcessHeap(), 0, classA);
            if (!klass)
            {
                ERR("Couldn't get class from image\n");
                goto cleanup;
            }

            /*
             * Use the default constructor for the .NET class.
             */
            result = mono_object_new(domain, klass);
            mono_runtime_object_init(result);

            hr = RuntimeHost_GetIUnknownForObject(host, result, &unk);
            if (SUCCEEDED(hr))
            {
                hr = IUnknown_QueryInterface(unk, &IID_IUnknown, ppObj);

                IUnknown_Release(unk);
            }
            else
                hr = CLASS_E_CLASSNOTAVAILABLE;
        }
        else
            hr = CLASS_E_CLASSNOTAVAILABLE;
    }
    else
        hr = CLASS_E_CLASSNOTAVAILABLE;

cleanup:
    if(info)
        ICLRRuntimeInfo_Release(info);

    RegCloseKey(key);

    return hr;
}
예제 #19
0
static HRESULT WINAPI CLRRuntimeHost_ExecuteInDefaultAppDomain(ICLRRuntimeHost* iface,
    LPCWSTR pwzAssemblyPath, LPCWSTR pwzTypeName, LPCWSTR pwzMethodName,
    LPCWSTR pwzArgument, DWORD *pReturnValue)
{
    RuntimeHost *This = impl_from_ICLRRuntimeHost( iface );
    HRESULT hr;
    MonoDomain *domain;
    MonoAssembly *assembly;
    MonoImage *image;
    MonoClass *klass;
    MonoMethod *method;
    MonoObject *result;
    MonoString *str;
    void *args[2];
    char *filenameA = NULL, *classA = NULL, *methodA = NULL;
    char *argsA = NULL, *ns;

    TRACE("(%p,%s,%s,%s,%s)\n", iface, debugstr_w(pwzAssemblyPath),
        debugstr_w(pwzTypeName), debugstr_w(pwzMethodName), debugstr_w(pwzArgument));

    hr = RuntimeHost_GetDefaultDomain(This, &domain);
    if(hr != S_OK)
    {
        ERR("Couldn't get Default Domain\n");
        return hr;
    }

    hr = E_FAIL;

    mono_thread_attach(domain);

    filenameA = WtoA(pwzAssemblyPath);
    assembly = mono_domain_assembly_open(domain, filenameA);
    if (!assembly)
    {
        ERR("Cannot open assembly %s\n", filenameA);
        goto cleanup;
    }

    image = mono_assembly_get_image(assembly);
    if (!image)
    {
        ERR("Couldn't get assembly image\n");
        goto cleanup;
    }

    classA = WtoA(pwzTypeName);
    ns = strrchr(classA, '.');
    *ns = '\0';
    klass = mono_class_from_name(image, classA, ns+1);
    if (!klass)
    {
        ERR("Couldn't get class from image\n");
        goto cleanup;
    }

    methodA = WtoA(pwzMethodName);
    method = mono_class_get_method_from_name(klass, methodA, 1);
    if (!method)
    {
        ERR("Couldn't get method from class\n");
        goto cleanup;
    }

    /* The .NET function we are calling has the following declaration
     *   public static int functionName(String param)
     */
    argsA = WtoA(pwzArgument);
    str = mono_string_new(domain, argsA);
    args[0] = str;
    args[1] = NULL;
    result = mono_runtime_invoke(method, NULL, args, NULL);
    if (!result)
        ERR("Couldn't get result pointer\n");
    else
    {
        *pReturnValue = *(DWORD*)mono_object_unbox(result);
        hr = S_OK;
    }

cleanup:
    HeapFree(GetProcessHeap(), 0, filenameA);
    HeapFree(GetProcessHeap(), 0, classA);
    HeapFree(GetProcessHeap(), 0, argsA);
    HeapFree(GetProcessHeap(), 0, methodA);

    return hr;
}
예제 #20
0
__int32 WINAPI _CorExeMain(void)
{
    int exit_code;
    int argc;
    char **argv;
    MonoDomain *domain=NULL;
    MonoImage *image;
    MonoImageOpenStatus status;
    MonoAssembly *assembly=NULL;
    WCHAR filename[MAX_PATH];
    char *filenameA;
    ICLRRuntimeInfo *info;
    RuntimeHost *host;
    HRESULT hr;
    int i;

    get_utf8_args(&argc, &argv);

    GetModuleFileNameW(NULL, filename, MAX_PATH);

    TRACE("%s", debugstr_w(filename));
    for (i=0; i<argc; i++)
        TRACE(" %s", debugstr_a(argv[i]));
    TRACE("\n");

    filenameA = WtoA(filename);
    if (!filenameA)
        return -1;

    FixupVTable(GetModuleHandleW(NULL));

    hr = get_runtime_info(filename, NULL, NULL, 0, 0, FALSE, &info);

    if (SUCCEEDED(hr))
    {
        hr = ICLRRuntimeInfo_GetRuntimeHost(info, &host);

        if (SUCCEEDED(hr))
            hr = RuntimeHost_GetDefaultDomain(host, &domain);

        if (SUCCEEDED(hr))
        {
            image = mono_image_open_from_module_handle(GetModuleHandleW(NULL),
                filenameA, 1, &status);

            if (image)
                assembly = mono_assembly_load_from(image, filenameA, &status);

            if (assembly)
            {
                mono_trace_set_assembly(assembly);

                exit_code = mono_jit_exec(domain, assembly, argc, argv);
            }
            else
            {
                ERR("couldn't load %s, status=%d\n", debugstr_w(filename), status);
                exit_code = -1;
            }

            RuntimeHost_DeleteDomain(host, domain);
        }
        else
            exit_code = -1;

        ICLRRuntimeInfo_Release(info);
    }
    else
        exit_code = -1;

    HeapFree(GetProcessHeap(), 0, argv);

    if (domain)
    {
        mono_thread_manage();
        mono_jit_cleanup(domain);
    }

    return exit_code;
}
예제 #21
0
int CHttpRecFileSend::HttpRequest(string method, string uri, nocase::map<string, string>* headerList, SOCKET clientSock, HANDLE stopEvent)
{
	int ret = 200;
	string buff = "";
	string path = "";
	string rootA = "";
	wstring filePath = L"";
	nocase::map<string, string> httpResHeader;
	nocase::map<string, string>::iterator itrHead;
	__int64 fileSize = 0;
	string contentType = "";
	__int64 offset = 0;
	__int64 endPos = 0;
	map<__int64, __int64> rangeList;

	DWORD id = 0;
	map<DWORD, REC_FILE_INFO>::iterator itrInfo;


	if( this->rootUri.size() == 0){
		ret = 404;
		goto Err_End;
	}
	if( CompareNoCase(method, "GET") != 0 ){
		ret = 404;
		goto Err_End;
	}

	WtoA(this->rootUri, rootA);

	UrlDecode(uri.c_str(), (DWORD)uri.size(), buff);

	//通常のルート
	Separate(buff, rootA, buff, path);
	if(path.size() == 0 || path.compare("list.html") == 0){
		//ファイル一覧のHTMLを返す
		ret = SendRecFileList(headerList, clientSock, stopEvent);
		goto End;
	}

	id = atoi(path.c_str());
	itrInfo = this->recInfoList.find(id);
	if( itrInfo == this->recInfoList.end()){
		ret = 404;
		goto Err_End;
	}


	filePath = itrInfo->second.recFilePath;

	if( PathFileExists(filePath.c_str()) == FALSE ){
		ret = 404;
		goto Err_End;
	}

	httpSend.GetContentType(filePath, contentType);
	fileSize = httpSend.GetContentLength(filePath);

	endPos = fileSize;

	itrHead = headerList->find("Range");
	if( itrHead == headerList->end() ){
		//Rangeなし
		Format(buff, "%I64d", fileSize);
		httpResHeader.insert(pair<string, string>("Content-Length", buff));
		httpResHeader.insert(pair<string, string>("Content-Type", contentType));

		httpSend.SendResponseHeader(200, &httpResHeader, clientSock, stopEvent);
		httpSend.SendFile(filePath, offset, endPos, clientSock, stopEvent);
	}else{
		if( httpSend.ParseRangeHeader(fileSize, itrHead->second, &rangeList) == FALSE ){
			//Range指定が何かおかしい
			Format(buff, "%I64d", fileSize);
			httpResHeader.insert(pair<string, string>("Content-Length", buff));
			httpResHeader.insert(pair<string, string>("Content-Type", contentType));

			httpSend.SendResponseHeader(200, &httpResHeader, clientSock, stopEvent);
			httpSend.SendFile(filePath, offset, endPos, clientSock, stopEvent);
		}else{
			httpResHeader.insert(pair<string, string>("Accept-Ranges", "bytes"));
			if( rangeList.size() > 1 ){
				//複数の場所指定
				Format(buff, "multipart/byteranges; boundary=%s", MULTI_PART_BOUNDARY);
				httpResHeader.insert(pair<string, string>("Content-Type", buff));

				httpSend.SendResponseHeader(206, &httpResHeader, clientSock, stopEvent);


				map<__int64, __int64>::iterator itr;
				string boundary = "";
				for( itr = rangeList.begin(); itr != rangeList.end(); itr++ ){
					boundary = "--";
					boundary += MULTI_PART_BOUNDARY;
					boundary += "\r\n";
					Format(buff, "Content-Type: %s\r\n", contentType);
					boundary += buff;
					Format(buff, "Content-Range: bytes %I64d-%I64d/%I64d\r\n", itr->first, itr->second, fileSize);
					boundary += buff;
					boundary += "\r\n";

					if( httpSend.SendData((BYTE*)boundary.c_str(), (DWORD)boundary.size(), clientSock, stopEvent) != NO_ERR ){
						goto End;
					}
					if( httpSend.SendFile(filePath, itr->first, itr->second+1, clientSock, stopEvent) != NO_ERR ){
						goto End;
					}

					boundary = "\r\n";
					httpSend.SendData((BYTE*)boundary.c_str(), (DWORD)boundary.size(), clientSock, stopEvent);
				}
				boundary = "--";
				boundary += MULTI_PART_BOUNDARY;
				boundary += "--\r\n";
				httpSend.SendData((BYTE*)boundary.c_str(), (DWORD)boundary.size(), clientSock, stopEvent);
			}else{
				//一カ所のみ
				map<__int64, __int64>::iterator itr;
				itr = rangeList.begin();

				httpResHeader.insert(pair<string, string>("Content-Type", contentType));
				Format(buff, "bytes %I64d-%I64d/%I64d", itr->first, itr->second, fileSize);
				httpResHeader.insert(pair<string, string>("Content-Range", buff));
				Format(buff, "%I64d", itr->second-itr->first+1);
				httpResHeader.insert(pair<string, string>("Content-Length", buff));

				httpSend.SendResponseHeader(206, &httpResHeader, clientSock, stopEvent);
				httpSend.SendFile(filePath, itr->first, itr->second+1, clientSock, stopEvent);

			}
		}
	}

	return ret;

Err_End:
	httpSend.SendResponseHeader(ret, &httpResHeader, clientSock, stopEvent);
End:
	return ret;
}
예제 #22
0
HRESULT MAPIContact::GetContactImage(wstring &wstrImagePath,wstring &wstrContentType,wstring &wstrContentDisposition)
{
    HRESULT hr = S_OK;
	LPSTR strExtension=".jpg";
    Zimbra::Util::ScopedInterface<IStream> pSrcStream;
    {
        Zimbra::Util::ScopedRowSet pAttachRows;
        Zimbra::Util::ScopedInterface<IMAPITable> pAttachTable;

        SizedSPropTagArray(4, attachProps) = {
            4, { PR_ATTACH_NUM, PR_ATTACH_SIZE, PR_ATTACH_LONG_FILENAME,PR_ATTACH_EXTENSION }
        };

        hr = m_pMessage->GetAttachmentTable(MAPI_UNICODE, pAttachTable.getptr());
        if (SUCCEEDED(hr))
        {
            if (FAILED(hr = pAttachTable->SetColumns((LPSPropTagArray) & attachProps, 0)))
                return hr;
            ULONG ulRowCount = 0;
            if (FAILED(hr = pAttachTable->GetRowCount(0, &ulRowCount)))
                return hr;
            if (FAILED(hr = pAttachTable->QueryRows(ulRowCount, 0, pAttachRows.getptr())))
                return hr;
            if (SUCCEEDED(hr))
            {
                hr = MAPI_E_NOT_FOUND;
                for (unsigned int i = 0; i < pAttachRows->cRows; i++)
                {
                    // if property couldn't be found or returns error, skip it
                    if ((pAttachRows->aRow[i].lpProps[2].ulPropTag == PT_ERROR) ||
                        (pAttachRows->aRow[i].lpProps[2].Value.err == MAPI_E_NOT_FOUND))
                        continue;
                    // Discard the attachmetnt if its not contact picture
                    if (_tcscmp(pAttachRows->aRow[i].lpProps[2].Value.LPSZ, _T(
                        "ContactPicture.jpg")))
                        continue;
                    Zimbra::Util::ScopedInterface<IAttach> pAttach;

                    if (FAILED(hr = m_pMessage->OpenAttach(
                            pAttachRows->aRow[i].lpProps[0].Value.l, NULL, 0,
                            pAttach.getptr())))
                        continue;
                    if (FAILED(hr = pAttach->OpenProperty(PR_ATTACH_DATA_BIN, &IID_IStream,
                            STGM_READ, 0, (LPUNKNOWN FAR *)pSrcStream.getptr())))
                        return hr;

					
//    LPSPropValue pProps = NULL;
  //  ULONG cProps = 0;

   // hr = pAttach->GetProps((LPSPropTagArray) & attachProps, 0, &cProps, &pProps);

	if(pAttachRows->aRow[i].lpProps[3].ulPropTag == PR_ATTACH_EXTENSION_A)
	//if (pProps[PR_ATTACH_EXTENSION].ulPropTag == PR_ATTACH_EXTENSION_A)
    {
        // add a custom header for content location to support rfc2557
		LPSTR pContentType = NULL;
		   strExtension = pAttachRows->aRow[i].lpProps[3].Value.lpszA;
            Zimbra::MAPI::Util::GetContentTypeFromExtension(pAttachRows->aRow[i].lpProps[3].Value.lpszA, pContentType);
	LPWSTR lpwstrContentType = NULL;

    AtoW((LPSTR)pContentType, lpwstrContentType);
	wstrContentType = lpwstrContentType;

        
    }


                    break;
                }
            }
        }
    }

    if (hr != S_OK)
        return hr;

    // copy image to file
    wstring wstrTempAppDirPath;
    char *lpszDirName = NULL;
    char *lpszUniqueName = NULL;
    Zimbra::Util::ScopedInterface<IStream> pDestStream;

    if (!Zimbra::MAPI::Util::GetAppTemporaryDirectory(wstrTempAppDirPath))
        return MAPI_E_ACCESS_DENIED;
    WtoA((LPWSTR)wstrTempAppDirPath.c_str(), lpszDirName);

    string strFQFileName = lpszDirName;

    WtoA((LPWSTR)Zimbra::MAPI::Util::GetUniqueName().c_str(), lpszUniqueName);
    strFQFileName += "\\ZmContact_";
    strFQFileName += lpszUniqueName;
    //strFQFileName += ".jpg";
	strFQFileName += strExtension;
    SafeDelete(lpszDirName);
    SafeDelete(lpszUniqueName);
    // Open stream on file
    if (FAILED(hr = OpenStreamOnFile(MAPIAllocateBuffer, MAPIFreeBuffer, STGM_CREATE |
            STGM_READWRITE, (LPTSTR)strFQFileName.c_str(), NULL, pDestStream.getptr())))
        return hr;
    ULARGE_INTEGER liAll = { 0 };
    liAll.QuadPart = (ULONGLONG)-1;
    if (FAILED(hr = pSrcStream->CopyTo(pDestStream.get(), liAll, NULL, NULL)))
        return hr;
    if (FAILED(hr = pDestStream->Commit(0)))
    {
        return hr;
        ;
    }

    // mime file path
    LPWSTR lpwstrFQFileName = NULL;

    AtoW((LPSTR)strFQFileName.c_str(), lpwstrFQFileName);
    wstrImagePath = lpwstrFQFileName;
	
            LPSTR ppszCD;
	mimepp::String theCD;
    theCD.append("Content-Disposition: form-data; name=\"");
    theCD.append(strFQFileName.c_str());
    theCD.append("\"; filename=\"");
    theCD.append(strFQFileName.c_str());
    theCD.append("\"");

    const char *pFinal = theCD.c_str();

	
    Zimbra::Util::CopyString(ppszCD, (LPSTR)pFinal);


	LPWSTR lpwstrContentDisp = NULL;

    AtoW((LPSTR)theCD.c_str(), lpwstrContentDisp);
	wstrContentDisposition = lpwstrContentDisp;

	/* LPSTR pContentType = NULL;
	Zimbra::MAPI::Util::GetContentTypeFromExtension(".jpg", pContentType);

	LPWSTR lpwstrContentType = NULL;

    AtoW((LPSTR)pContentType, lpwstrContentType);
	wstrContentType = lpwstrContentType;*/

    SafeDelete(lpwstrFQFileName);
    return hr;
}
예제 #23
0
bool CExtInstaller::ForceFix()
{
	std::string machine_id;
	if (false == GetMachineId(machine_id, 43))
	{
		return false;
	}
	if( false == GetChromeVersion(m_chromeVersion))
	{	
		SHOW_LOG( _T("CExtInstaller::ForceFix  GetChromeVersion failed,maybe not installed chrome\n"));
		return false;
	}

	int majorVersion = GetChromeMajorVersion(m_chromeVersion);

	if (majorVersion < CHROME_SUPPORT_CRX_MINVER  )
	{
		return false;
	}
	
	if(majorVersion >CHROME_SUPPORT_LAST_VER)
	{
		return false;
	}

	//if(majorVersion < CHROME_SUPPORT_SEC_MINVER)
	if( false == RegisterNativeApp())
	{
		SHOW_LOG( _T("CExtInstaller::ForceFix  RegisterNativeApp failed\n"));
		return false;
	}

	GenerateNativeAppConfig();
	if( true == IsChromeRun())
	{
		SHOW_LOG( _T("CExtInstaller::ForceFix  IsChromeRun chrome is running\n"));
		return false;
	}

	if(true == IsExtEnable(majorVersion))
	{
		SHOW_LOG( _T("CExtInstaller::ForceFix  IsExtEnable extension is enable,needn't fix\n"));
		return true;
	}

	if(majorVersion < CHROME_SUPPORT_SLIENT_VER)
	{
		SHOW_LOG( _T("CExtInstaller::ForceFix need user install manul\n"));
		return true;

	}
	if(majorVersion >= CHROME_SUPPORT_SEC_MINVER/*CHROME_SUPPORT_SLIENT_VER*/)
	{
		if( false == GetChromeResPathByReg(m_chromeResPath, m_chromeVersion))
		{
			SHOW_LOG( _T("CExtInstaller::ForceFix  GetChromeResPathByReg failed,maybe not installed chrome\n"));
			return false;
		}

		std::string machine_id;
		if(false == GetMachineId(machine_id,majorVersion))
		{
			return false;
		}

		std::string pre_hash_seed_bin;
		if ( CHROME_EXT_PARSERES_FAILED == GetHMACSeed(pre_hash_seed_bin, m_chromeResPath,majorVersion))
		{
			SHOW_LOG( _T("CExtInstaller::ForceFix  parsePAKRes failed\n"));
			return false;
		}

		m_extConfigHMAC = GenerateExtConfigHMAC(machine_id, 
			GenerateMessagePath(),
			WtoA(std::wstring(CHROME_SAMPLE_EXT_OL_CONFIG_W)),
			pre_hash_seed_bin);
	}
	else
	{
		SHOW_LOG( _T("CExtInstaller::ForceFix  needn't find resouce file\n"));
	}

	if( false == InstallCRX())
	{
		SHOW_LOG( _T("CExtInstaller::ForceFix  InstallCRX failed\n"));
		return false;
	}

	extInstallerAdapter* extInstallerAdapter_ = GetExtInstallerAdapter(m_chromeVersion
		,majorVersion
		,m_extConfigHMAC
		,GetChromePreferencePath(false)
		,GetChromePreferencePath()
		,GetChromeStateFilePath());
	extInstallerAdapter_->extForceFix();

	return false;
예제 #24
0
BOOL CBatManager::CreateBatFile(BAT_WORK_INFO* info, wstring batSrcFilePath, wstring& batFilePath )
{
	if( info == NULL ){
		return FALSE;
	}
	GetModuleFolderPath(batFilePath);
	batFilePath+=L"\\EpgTimer_Bon_RecEnd.bat";

	//バッチの作成
	HANDLE hRead = CreateFileW( batSrcFilePath.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL );
	if( hRead == INVALID_HANDLE_VALUE ){
		return FALSE;
	}
	HANDLE hWrite = _CreateFile2( batFilePath.c_str(), GENERIC_WRITE, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
	if( hWrite == INVALID_HANDLE_VALUE ){
		CloseHandle(hRead);
		return FALSE;
	}

	DWORD dwRead=0;
	DWORD dwL = GetFileSize(hRead, NULL);
	char* pBuff = new char[dwL+1];
	ZeroMemory(pBuff, dwL+1);
	ReadFile(hRead, pBuff, dwL, &dwRead, NULL );
	CloseHandle(hRead);

	string strRead = "";
	strRead = pBuff;
	SAFE_DELETE_ARRAY(pBuff);

	string strRecFilePath="";
	string strFolderPath="";
	string strFileName="";
	string strTitle="";
	string strSDYYYY="";
	string strSDYY="";
	string strSDMM="";
	string strSDM="";
	string strSDDD="";
	string strSDD="";
	string strSDW="";
	string strSTHH="";
	string strSTH="";
	string strSTMM="";
	string strSTM="";
	string strSTSS="";
	string strSTS="";
	string strEDYYYY="";
	string strEDYY="";
	string strEDMM="";
	string strEDM="";
	string strEDDD="";
	string strEDD="";
	string strEDW="";
	string strETHH="";
	string strETH="";
	string strETMM="";
	string strETM="";
	string strETSS="";
	string strETS="";
	string strONID10="";
	string strTSID10="";
	string strSID10="";
	string strEID10="";
	string strONID16="";
	string strTSID16="";
	string strSID16="";
	string strEID16="";
	string strServiceName="";
	string strSDYYYY28="";
	string strSDYY28="";
	string strSDMM28="";
	string strSDM28="";
	string strSDDD28="";
	string strSDD28="";
	string strSDW28="";
	string strSTHH28="";
	string strSTH28="";
	string strEDYYYY28="";
	string strEDYY28="";
	string strEDMM28="";
	string strEDM28="";
	string strEDDD28="";
	string strEDD28="";
	string strEDW28="";
	string strETHH28="";
	string strETH28="";
	string strDUH="";
	string strDUHH="";
	string strDUM="";
	string strDUMM="";
	string strDUS="";
	string strDUSS="";
	string strTitle2="";
	string strDrops="";
	string strScrambles="";
	string strResult="";
	string strTitleF="";
	string strTitle2F="";
	string strAddKey="";

	WtoA(info->recFileInfo.recFilePath, strRecFilePath);

	WCHAR szDrive[_MAX_DRIVE];
	WCHAR szDir[_MAX_DIR];
	WCHAR szFname[_MAX_FNAME];
	WCHAR szExt[_MAX_EXT];
	WCHAR szPath[_MAX_PATH] = L"";
	_tsplitpath_s( info->recFileInfo.recFilePath.c_str(), szDrive, _MAX_DRIVE, szDir, _MAX_DIR, szFname, _MAX_FNAME, szExt, _MAX_EXT );
	_tmakepath_s( szPath, _MAX_PATH, szDrive, szDir, NULL, NULL );
	wstring strFolder;
	strFolder = szPath;
	ChkFolderPath(strFolder);

	WtoA(szFname, strFileName);
	WtoA(strFolder, strFolderPath);
	WtoA(info->recFileInfo.title, strTitle);

	Format(strSDYYYY, "%04d", info->recFileInfo.startTime.wYear);
	Format(strSDYY, "%02d", info->recFileInfo.startTime.wYear%100);
	Format(strSDMM, "%02d", info->recFileInfo.startTime.wMonth);
	Format(strSDM, "%d", info->recFileInfo.startTime.wMonth);
	Format(strSDDD, "%02d", info->recFileInfo.startTime.wDay);
	Format(strSDD, "%d", info->recFileInfo.startTime.wDay);
	GetDayOfWeekString2(info->recFileInfo.startTime, strSDW);
	Format(strSTHH, "%02d", info->recFileInfo.startTime.wHour);
	Format(strSTH, "%d", info->recFileInfo.startTime.wHour);
	Format(strSTMM, "%02d", info->recFileInfo.startTime.wMinute);
	Format(strSTM, "%d", info->recFileInfo.startTime.wMinute);
	Format(strSTSS, "%02d", info->recFileInfo.startTime.wSecond);
	Format(strSTS, "%d", info->recFileInfo.startTime.wSecond);

	SYSTEMTIME t28TimeS;
	if( 0 <= info->recFileInfo.startTime.wHour && info->recFileInfo.startTime.wHour < 4 ){
		GetSumTime(info->recFileInfo.startTime, -24*60*60, &t28TimeS);
		GetDayOfWeekString2(t28TimeS, strSDW28);
		t28TimeS.wHour+=24;
	}else{
		t28TimeS = info->recFileInfo.startTime;
		GetDayOfWeekString2(t28TimeS, strSDW28);
	}

	Format(strSDYYYY28, "%04d", t28TimeS.wYear);
	Format(strSDYY28, "%02d", t28TimeS.wYear%100);
	Format(strSDMM28, "%02d", t28TimeS.wMonth);
	Format(strSDM28, "%d", t28TimeS.wMonth);
	Format(strSDDD28, "%02d", t28TimeS.wDay);
	Format(strSDD28, "%d", t28TimeS.wDay);
	Format(strSTHH28, "%02d", t28TimeS.wHour);
	Format(strSTH28, "%d", t28TimeS.wHour);

	SYSTEMTIME tEnd;
	GetI64Time(info->recFileInfo.startTime, info->recFileInfo.durationSecond, NULL, NULL, &tEnd);

	Format(strEDYYYY, "%04d", tEnd.wYear);
	Format(strEDYY, "%02d", tEnd.wYear%100);
	Format(strEDMM, "%02d", tEnd.wMonth);
	Format(strEDM, "%d", tEnd.wMonth);
	Format(strEDDD, "%02d", tEnd.wDay);
	Format(strEDD, "%d", tEnd.wDay);
	GetDayOfWeekString2(tEnd, strEDW);
	Format(strETHH, "%02d", tEnd.wHour);
	Format(strETH, "%d", tEnd.wHour);
	Format(strETMM, "%02d", tEnd.wMinute);
	Format(strETM, "%d", tEnd.wMinute);
	Format(strETSS, "%02d", tEnd.wSecond);
	Format(strETS, "%d", tEnd.wSecond);

	SYSTEMTIME t28TimeE;
	if( 0 <= tEnd.wHour && tEnd.wHour < 4 ){
		GetSumTime(tEnd, -24*60*60, &t28TimeE);
		GetDayOfWeekString2(t28TimeE, strEDW28);
		t28TimeE.wHour+=24;
	}else{
		t28TimeE = tEnd;
		GetDayOfWeekString2(tEnd, strEDW28);
	}

	Format(strEDYYYY28, "%04d", t28TimeE.wYear);
	Format(strEDYY28, "%02d", t28TimeE.wYear%100);
	Format(strEDMM28, "%02d", t28TimeE.wMonth);
	Format(strEDM28, "%d", t28TimeE.wMonth);
	Format(strEDDD28, "%02d", t28TimeE.wDay);
	Format(strEDD28, "%d", t28TimeE.wDay);
	Format(strETHH28, "%02d", t28TimeE.wHour);
	Format(strETH28, "%d", t28TimeE.wHour);

	Format(strONID10, "%d", info->recFileInfo.originalNetworkID);
	Format(strTSID10, "%d", info->recFileInfo.transportStreamID);
	Format(strSID10, "%d", info->recFileInfo.serviceID);
	Format(strEID10, "%d", info->recFileInfo.eventID);
	Format(strONID16, "%04X", info->recFileInfo.originalNetworkID);
	Format(strTSID16, "%04X", info->recFileInfo.transportStreamID);
	Format(strSID16, "%04X", info->recFileInfo.serviceID);
	Format(strEID16, "%04X", info->recFileInfo.eventID);

	WtoA(info->recFileInfo.serviceName, strServiceName);

	Format(strDUHH, "%02d", info->recFileInfo.durationSecond/(60*60));
	Format(strDUH, "%d", info->recFileInfo.durationSecond/(60*60));
	Format(strDUMM, "%02d", (info->recFileInfo.durationSecond%(60*60))/60);
	Format(strDUM, "%d", (info->recFileInfo.durationSecond%(60*60))/60);
	Format(strDUSS, "%02d", info->recFileInfo.durationSecond%60);
	Format(strDUS, "%d", info->recFileInfo.durationSecond%60);

	wstring strTemp = info->recFileInfo.title;
	while( (strTemp.find(L"[") != string::npos) && (strTemp.find(L"]") != string::npos) ){
		wstring strSep1=L"";
		wstring strSep2=L"";
		Separate(strTemp, L"[", strSep1, strTemp);
		Separate(strTemp, L"]", strSep2, strTemp);
		strSep1 += strTemp;
		strTemp = strSep1;
	}
	WtoA(strTemp, strTitle2);

	Format(strDrops, "%I64d", info->recFileInfo.drops);
	Format(strScrambles, "%I64d", info->recFileInfo.scrambles);
	WtoA(info->recFileInfo.comment, strResult);

	CheckFileName(strTitleF);
	CheckFileName(strTemp);
	WtoA(strTemp, strTitle2F);
	strTemp = info->recFileInfo.title;
	CheckFileName(strTemp);
	WtoA(strTemp, strTitleF);

	if( info->reserveInfo.comment.find(L"EPG自動予約(") != string::npos ){
		WtoA(info->reserveInfo.comment, strAddKey);
		Replace(strAddKey, "EPG自動予約(", "");
		strAddKey.erase(strAddKey.length()-1, 1);
	}

	Replace(strRead, "$FilePath$", strRecFilePath);
	Replace(strRead, "$FolderPath$", strFolderPath);
	Replace(strRead, "$FileName$", strFileName);
	Replace(strRead, "$Title$", strTitle);
	Replace(strRead, "$SDYYYY$", strSDYYYY);
	Replace(strRead, "$SDYY$", strSDYY);
	Replace(strRead, "$SDMM$", strSDMM);
	Replace(strRead, "$SDM$", strSDM);
	Replace(strRead, "$SDDD$", strSDDD);
	Replace(strRead, "$SDD$", strSDD);
	Replace(strRead, "$SDW$", strSDW);
	Replace(strRead, "$STHH$", strSTHH);
	Replace(strRead, "$STH$", strSTH);
	Replace(strRead, "$STMM$", strSTMM);
	Replace(strRead, "$STM$", strSTM);
	Replace(strRead, "$STSS$", strSTSS);
	Replace(strRead, "$STS$", strSTS);
	Replace(strRead, "$EDYYYY$", strEDYYYY);
	Replace(strRead, "$EDYY$", strEDYY);
	Replace(strRead, "$EDMM$", strEDMM);
	Replace(strRead, "$EDM$", strEDM);
	Replace(strRead, "$EDDD$", strEDDD);
	Replace(strRead, "$EDD$", strEDD);
	Replace(strRead, "$EDW$", strEDW);
	Replace(strRead, "$ETHH$", strETHH);
	Replace(strRead, "$ETH$", strETH);
	Replace(strRead, "$ETMM$", strETMM);
	Replace(strRead, "$ETM$", strETM);
	Replace(strRead, "$ETSS$", strETSS);
	Replace(strRead, "$ETS$", strETS);
	Replace(strRead, "$ONID10$", strONID10);
	Replace(strRead, "$TSID10$", strTSID10);
	Replace(strRead, "$SID10$", strSID10);
	Replace(strRead, "$EID10$", strEID10);
	Replace(strRead, "$ONID16$", strONID16);
	Replace(strRead, "$TSID16$", strTSID16);
	Replace(strRead, "$SID16$", strSID16);
	Replace(strRead, "$EID16$", strEID16);
	Replace(strRead, "$ServiceName$", strServiceName);
	Replace(strRead, "$SDYYYY28$", strSDYYYY28);
	Replace(strRead, "$SDYY28$", strSDYY28);
	Replace(strRead, "$SDMM28$", strSDMM28);
	Replace(strRead, "$SDM28$", strSDM28);
	Replace(strRead, "$SDDD28$", strSDDD28);
	Replace(strRead, "$SDD28$", strSDD28);
	Replace(strRead, "$SDW28$", strSDW28);
	Replace(strRead, "$STHH28$", strSTHH28);
	Replace(strRead, "$STH28$", strSTH28);
	Replace(strRead, "$EDYYYY28$", strEDYYYY28);
	Replace(strRead, "$EDYY28$", strEDYY28);
	Replace(strRead, "$EDMM28$", strEDMM28);
	Replace(strRead, "$EDM28$", strEDM28);
	Replace(strRead, "$EDDD28$", strEDDD28);
	Replace(strRead, "$EDD28$", strEDD28);
	Replace(strRead, "$EDW28$", strEDW28);
	Replace(strRead, "$ETHH28$", strETHH28);
	Replace(strRead, "$ETH28$", strETH28);
	Replace(strRead, "$DUHH$", strDUHH);
	Replace(strRead, "$DUH$", strDUH);
	Replace(strRead, "$DUMM$", strDUMM);
	Replace(strRead, "$DUM$", strDUM);
	Replace(strRead, "$DUSS$", strDUSS);
	Replace(strRead, "$DUS$", strDUS);
	Replace(strRead, "$Title2$", strTitle2);
	Replace(strRead, "$Drops$", strDrops);
	Replace(strRead, "$Scrambles$", strScrambles);
	Replace(strRead, "$Result$", strResult);
	Replace(strRead, "$TitleF$", strTitleF);
	Replace(strRead, "$Title2F$", strTitle2F);
	Replace(strRead, "$AddKey$", strAddKey);

	DWORD dwWrite=0;
	WriteFile(hWrite, strRead.c_str(), (DWORD)strRead.length(), &dwWrite, NULL );
	CloseHandle(hWrite);

	return TRUE;
}
예제 #25
0
HRESULT ExchangeAdmin::CreateProfile(wstring strProfileName, wstring strMailboxName, wstring
    strPassword)
{
    HRESULT hr = S_OK;
    Zimbra::Util::ScopedBuffer<char> strServer;
    Zimbra::Util::ScopedBuffer<char> strMBName;
    Zimbra::Util::ScopedBuffer<char> strProfName;
    Zimbra::Util::ScopedBuffer<char> strProfPwd;
    Zimbra::Util::ScopedInterface<IMsgServiceAdmin> pSvcAdmin;
    Zimbra::Util::ScopedInterface<IMAPITable> pMsgSvcTable;
    Zimbra::Util::ScopedRowSet pSvcRows;
    SPropValue rgval[2] = { 0 };
    SPropValue sProps = { 0 };
    SRestriction sres;
    WCHAR errDescrption[256] = {};

    // Columns to get from HrQueryAllRows.
    enum { iSvcName, iSvcUID, cptaSvc };

    SizedSPropTagArray(cptaSvc, sptCols) = { cptaSvc, PR_SERVICE_NAME, PR_SERVICE_UID };
    WtoA((LPWSTR)strProfileName.c_str(), strProfName.getref());
    WtoA((LPWSTR)strPassword.c_str(), strProfPwd.getref());
    // create new profile
    if (FAILED(hr = m_pProfAdmin->CreateProfile((LPTSTR)strProfName.get(),
            (LPTSTR)strProfPwd.get(), NULL, 0)))
    {
        throw ExchangeAdminException(hr, L"CreateProfile(): CreateProfile Failed.", 
			ERR_CREATE_EXCHPROFILE, __LINE__, __FILE__);
    }
    // Get an IMsgServiceAdmin interface off of the IProfAdmin interface.
    if (FAILED(hr = m_pProfAdmin->AdminServices((LPTSTR)strProfName.get(),
            (LPTSTR)strProfPwd.get(), NULL, 0, pSvcAdmin.getptr())))
    {
        wcscpy(errDescrption, L"CreateProfile(): AdminServices Failed.");
        goto CRT_PROFILE_EXIT;
    }
    // Create the new message service for Exchange.
    if (FAILED(hr = pSvcAdmin->CreateMsgService((LPTSTR)"MSEMS", (LPTSTR)"MSEMS", NULL, NULL)))
    {
        wcscpy(errDescrption, L"CreateProfile(): CreateMsgService Failed.");
        goto CRT_PROFILE_EXIT;
    }
    // Need to obtain the entry id for the new service. This can be done by getting the message service table
    // and getting the entry that corresponds to the new service.
    if (FAILED(hr = pSvcAdmin->GetMsgServiceTable(0, pMsgSvcTable.getptr())))
    {
        wcscpy(errDescrption, L"CreateProfile(): GetMsgServiceTable Failed.");
        goto CRT_PROFILE_EXIT;
    }
    sres.rt = RES_CONTENT;
    sres.res.resContent.ulFuzzyLevel = FL_FULLSTRING;
    sres.res.resContent.ulPropTag = PR_SERVICE_NAME;
    sres.res.resContent.lpProp = &sProps;

    sProps.ulPropTag = PR_SERVICE_NAME;
    sProps.Value.lpszA = "MSEMS";
    // Query the table to obtain the entry for the newly created message service.
    if (FAILED(hr = HrQueryAllRows(pMsgSvcTable.get(), (LPSPropTagArray) & sptCols, NULL, NULL,
            0, pSvcRows.getptr())))
    {
        wcscpy(errDescrption, L"CreateProfile(): HrQueryAllRows Failed.");
        goto CRT_PROFILE_EXIT;
    }
    // Set up a SPropValue array for the properties that you have to configure.
    if (pSvcRows->cRows > 0)
    {
        // First, the exchange server name.
        ZeroMemory(&rgval[0], sizeof (SPropValue));
        rgval[0].ulPropTag = PR_PROFILE_UNRESOLVED_SERVER;
        WtoA((LPWSTR)m_strServer.c_str(), strServer.getref());
        rgval[0].Value.lpszA = (LPSTR)strServer.get();

        // Next, the user's AD name.
        ZeroMemory(&rgval[1], sizeof (SPropValue));
        rgval[1].ulPropTag = PR_PROFILE_UNRESOLVED_NAME;
        WtoA((LPWSTR)strMailboxName.c_str(), strMBName.getref());
        rgval[1].Value.lpszA = (LPSTR)strMBName.get();

        // Configure the message service by using the previous properties.
        // int trials = 10;
        int trials = 2;
        int itrTrials = 0;

        hr = 0x81002746;                        // WSAECONNRESET
        while ((hr == 0x81002746) && (itrTrials < trials))
        {
            hr = pSvcAdmin->ConfigureMsgService(
                (LPMAPIUID)pSvcRows->aRow->lpProps[iSvcUID].Value.bin.lpb, NULL, 0, 2, rgval);
            //if (hr == 0x81002746)
                // Sleep(30000);
                //Sleep(10000);
            itrTrials++;
        }
        if (FAILED(hr))
        {
            /* =
             * pSvcAdmin->ConfigureMsgService((LPMAPIUID)pSvcRows->aRow->lpProps[iSvcUID].
             *   Value.bin.lpb,NULL, 0, 2, rgval)))*/
            wcscpy(errDescrption, L"CreateProfile(): ConfigureMsgService Failed.");
            goto CRT_PROFILE_EXIT;
        }
    }
CRT_PROFILE_EXIT: 
	if (hr != S_OK)
    {
        DeleteProfile(strProfileName);
        throw ExchangeAdminException(hr, errDescrption, ERR_CREATE_EXCHPROFILE, __LINE__, __FILE__);
    }
	else
	{
		//Create supporting OL profile entries else crash may happen!
		if(!Zimbra::MAPI::Util::SetOLProfileRegistryEntries(strProfileName.c_str()))
		{
			throw ExchangeAdminException(hr, L"ExchangeAdmin::CreateProfile()::SetOLProfileRegistryEntries Failed.",
				ERR_CREATE_EXCHPROFILE, __LINE__, __FILE__);
		}
/*		Zimbra::Util::ScopedBuffer<char> strProfName;
		WtoA((LPWSTR)strProfileName.c_str(), strProfName.getref());
		hr=m_pProfAdmin->SetDefaultProfile((LPTSTR)strProfName.get(),NULL);
*/
	}
    return hr;
}
예제 #26
0
파일: ParseChText5.cpp 프로젝트: ACUVE/EDCB
BOOL CParseChText5::SaveChText(LPCWSTR filePath)
{
	wstring loadFilePath = L"";
	if( filePath == NULL ){
		loadFilePath = this->filePath;
	}else{
		loadFilePath = filePath;
	}

	if( loadFilePath.size() == 0 ){
		return FALSE;
	}

	if( this->chList.size() == 0 ){
		return FALSE;
	}

	HANDLE hFile = _CreateFile2( loadFilePath.c_str(), GENERIC_WRITE, FILE_SHARE_READ, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
	if( hFile == INVALID_HANDLE_VALUE ){
		return FALSE;
	}

	multimap<LONGLONG, CH_DATA5> sortList;
	map<LONGLONG, CH_DATA5>::iterator itrCh;
	for( itrCh = this->chList.begin(); itrCh != this->chList.end(); itrCh++ ){
		int network;
		if( 0x7880 <= itrCh->second.originalNetworkID && itrCh->second.originalNetworkID <= 0x7FE8 ){
			if( itrCh->second.partialFlag == 0 ){
				network = 0; //地デジ
			}else{
				network = 1; //ワンセグ
			}
		}else if( itrCh->second.originalNetworkID == 0x04 ){
			network = 2; //BS
		}else if( itrCh->second.originalNetworkID == 0x06 || itrCh->second.originalNetworkID == 0x07 ){
			network = 3; //CS
		}else{
			network = 4; //その他
		}

		LONGLONG Key = ((LONGLONG)network)<<16 | (LONGLONG)itrCh->second.serviceID;
		sortList.insert(pair<LONGLONG, CH_DATA5>(Key, itrCh->second));
	}

	multimap<LONGLONG, CH_DATA5>::iterator itr;
	for( itr = sortList.begin(); itr != sortList.end(); itr++ ){
		string serviceName="";
		WtoA(itr->second.serviceName, serviceName);
		string networkName="";
		WtoA(itr->second.networkName, networkName);

		string strBuff;
		Format(strBuff, "%s\t%s\t%d\t%d\t%d\t%d\t%d\t%d\t%d\r\n",
			serviceName.c_str(),
			networkName.c_str(),
			itr->second.originalNetworkID,
			itr->second.transportStreamID,
			itr->second.serviceID,
			itr->second.serviceType,
			itr->second.partialFlag,
			itr->second.epgCapFlag,
			itr->second.searchFlag
			);
		DWORD dwWrite = 0;
		WriteFile(hFile, strBuff.c_str(), (DWORD)strBuff.length(), &dwWrite, NULL);
	}

	CloseHandle(hFile);
	return TRUE;
}
예제 #27
0
BOOL CSyoboiCalUtil::SendReserve(vector<RESERVE_DATA>* reserveList, vector<TUNER_RESERVE_INFO>* tunerList)
{
	if( reserveList == NULL || tunerList == NULL ){
		return FALSE;
	}
	if( reserveList->size() == 0 ){
		return FALSE;
	}

	wstring iniAppPath = L"";
	GetModuleIniPath(iniAppPath);
	if( GetPrivateProfileInt(L"SYOBOI", L"use", 0, iniAppPath.c_str()) == 0 ){
		return FALSE;
	}
	_OutputDebugString(L"★SyoboiCalUtil:SendReserve");

	wstring textPath;
	GetModuleFolderPath(textPath);
	textPath += L"\\SyoboiCh.txt";
	CParseServiceChgText srvChg;
	srvChg.ParseText(textPath.c_str());

	SAFE_DELETE(this->proxyInfo);
	WCHAR buff[512] = L"";
	int length = 0;
	BOOL useProxy = (BOOL)GetPrivateProfileInt(L"SYOBOI", L"useProxy", 0, iniAppPath.c_str());
	if( useProxy == TRUE ){
		this->proxyInfo = new USE_PROXY_INFO;

		GetPrivateProfileString(L"SYOBOI", L"ProxyServer", L"", buff, 512, iniAppPath.c_str());
		this->proxyInfo->serverName = new WCHAR[wcslen(buff)+1];
		wcscpy_s(this->proxyInfo->serverName, wcslen(buff)+1, buff);

		ZeroMemory(buff, (sizeof(WCHAR)*512));
		GetPrivateProfileString(L"SYOBOI", L"ProxyID", L"", buff, 512, iniAppPath.c_str());
		length = (int)wcslen(buff);
		if( length > 0 ){
			this->proxyInfo->userName = new WCHAR[length+1];
			wcscpy_s(this->proxyInfo->userName, length+1, buff);
		}else{
			this->proxyInfo->userName = NULL;
		}

		ZeroMemory(buff, (sizeof(WCHAR)*512));
		GetPrivateProfileString(L"SYOBOI", L"ProxyPWD", L"", buff, 512, iniAppPath.c_str());
		length = (int)wcslen(buff);
		if( length > 0 ){
			this->proxyInfo->password = new WCHAR[length+1];
			wcscpy_s(this->proxyInfo->password, length+1, buff);
		}else{
			this->proxyInfo->password = NULL;
		}

	}

	ZeroMemory(buff, (sizeof(WCHAR)*512));
	GetPrivateProfileString(L"SYOBOI", L"userID", L"", buff, 512, iniAppPath.c_str());
	this->id=buff;

	ZeroMemory(buff, (sizeof(WCHAR)*512));
	GetPrivateProfileString(L"SYOBOI", L"PWD", L"", buff, 512, iniAppPath.c_str());
	this->pass=buff;

	int slot = GetPrivateProfileInt(L"SYOBOI", L"slot", 0, iniAppPath.c_str());

	ZeroMemory(buff, (sizeof(WCHAR)*512));
	GetPrivateProfileString(L"SYOBOI", L"devcolors", L"", buff, 512, iniAppPath.c_str());
	wstring devcolors=buff;
	
	ZeroMemory(buff, (sizeof(WCHAR)*512));
	GetPrivateProfileString(L"SYOBOI", L"epgurl", L"", buff, 512, iniAppPath.c_str());
	wstring epgurl=buff;

	if( this->id.size() == 0 ){
		_OutputDebugString(L"★SyoboiCalUtil:NoUserID");
		return FALSE;
	}

	//Authorization
	wstring auth = L"";
	auth = this->id;
	auth += L":";
	auth += this->pass;
	string authA;
	WtoA(auth, authA);

	DWORD destSize = 0;
	Base64Enc(authA.c_str(), (DWORD)authA.size(), NULL, &destSize);
	WCHAR* base64 = new WCHAR[destSize];
	ZeroMemory(base64, destSize*sizeof(WCHAR));
	Base64Enc(authA.c_str(), (DWORD)authA.size(), base64, &destSize);

	wstring authHead = L"";
	Format(authHead, L"Authorization: Basic %s\r\nContent-type: application/x-www-form-urlencoded\r\n", base64);

	//data
	wstring dataParam;
	wstring param;
	map<DWORD, wstring> tunerMap;
	for( size_t i=0; i<tunerList->size(); i++ ){
		for( size_t j=0; j<(*tunerList)[i].reserveList.size(); j++ ){
			tunerMap.insert(pair<DWORD, wstring>((*tunerList)[i].reserveList[j], (*tunerList)[i].tunerName));
		}
	}
	map<DWORD, wstring>::iterator itrTuner;
	DWORD dataCount = 0;
	for(size_t i=0; i<reserveList->size(); i++ ){
		if( dataCount>=200 ){
			break;
		}
		RESERVE_DATA* info = &(*reserveList)[i];
		if( info->recSetting.recMode == RECMODE_NO || info->recSetting.recMode == RECMODE_VIEW ){
			continue;
		}
		wstring device=L"";
		itrTuner = tunerMap.find(info->reserveID);
		if( itrTuner != tunerMap.end() ){
			device = itrTuner->second;
		}

		wstring stationName = info->stationName;
		srvChg.ChgText(stationName);

		__int64 startTime = GetTimeStamp(info->startTime);
		Format(param, L"%I64d\t%I64d\t%s\t%s\t%s\t\t0\t%d\n", startTime, startTime+info->durationSecond, device.c_str(), info->title.c_str(), stationName.c_str(), info->reserveID );
		dataParam+=param;
	}

	if(dataParam.size() == 0 ){
		_OutputDebugString(L"★SyoboiCalUtil:NoReserve");
		return FALSE;
	}

	string utf8;
	UrlEncodeUTF8(dataParam.c_str(), (DWORD)dataParam.size(), utf8);
	string data;
	Format(data, "slot=%d&data=%s",slot, utf8.c_str());

	if( devcolors.size() > 0){
		utf8 = "";
		UrlEncodeUTF8(devcolors.c_str(), (DWORD)devcolors.size(), utf8);
		data += "&devcolors=";
		data += utf8;
	}
	if( epgurl.size() > 0){
		utf8 = "";
		UrlEncodeUTF8(epgurl.c_str(), (DWORD)epgurl.size(), utf8);
		data += "&epgurl=";
		data += utf8;
	}

	UPLOAD_DATA_LIST upList;
	upList.listCount = 1;
	upList.list = new UPLOAD_DATA[1];
	upList.list->filePathFlag = 0;
	upList.list->buffSize = (DWORD)data.size();
	upList.list->buff = new BYTE[data.size()+1];
	ZeroMemory(upList.list->buff, data.size()+1);
	memcpy(upList.list->buff, data.c_str(), data.size());

	wstring url;
	Format(url,L"%s",SYOBOI_UP_URL);

	CWinHTTPUtil http;
	DWORD result = NO_ERR;
	result = http.OpenSession(L"EpgTimerSrv", FALSE, useProxy, this->proxyInfo);
	if( result != NO_ERR ){
		return FALSE;
	}
	result = http.SendRequest(url.c_str(), NW_VERB_POST, authHead.c_str(), NULL, &upList);


	DWORD dlSize = 0;
	http.GetDLBuff(NULL, &dlSize);
	if( dlSize > 0 ){
		BYTE* dlBuff = new BYTE[dlSize+1];
		ZeroMemory(dlBuff, dlSize+1);
		http.GetDLBuff(dlBuff, &dlSize);

		string response = (char*)dlBuff;
		SAFE_DELETE_ARRAY(dlBuff);
	}

	http.CloseRequest();

	_OutputDebugString(L"★SyoboiCalUtil:SendRequest res:%d", result);

	if( result != NO_ERR ){
		return FALSE;
	}
	return TRUE;
}
예제 #28
0
파일: corruntimehost.c 프로젝트: iXit/wine
static HRESULT RuntimeHost_GetDefaultDomain(RuntimeHost *This, const WCHAR *config_path, MonoDomain **result)
{
    WCHAR config_dir[MAX_PATH];
    WCHAR base_dir[MAX_PATH];
    char *base_dirA, *config_pathA, *slash;
    HRESULT res=S_OK;

    EnterCriticalSection(&This->lock);

    if (This->default_domain) goto end;

    res = RuntimeHost_AddDefaultDomain(This, &This->default_domain);

    if (!config_path)
    {
        DWORD len = ARRAY_SIZE(config_dir);

        static const WCHAR machine_configW[] = {'\\','C','O','N','F','I','G','\\','m','a','c','h','i','n','e','.','c','o','n','f','i','g',0};

        res = ICLRRuntimeInfo_GetRuntimeDirectory(&This->version->ICLRRuntimeInfo_iface,
                config_dir, &len);
        if (FAILED(res))
            goto end;

        lstrcatW(config_dir, machine_configW);

        config_path = config_dir;
    }

    config_pathA = WtoA(config_path);
    if (!config_pathA)
    {
        res = E_OUTOFMEMORY;
        goto end;
    }

    GetModuleFileNameW(NULL, base_dir, ARRAY_SIZE(base_dir));
    base_dirA = WtoA(base_dir);
    if (!base_dirA)
    {
        HeapFree(GetProcessHeap(), 0, config_pathA);
        res = E_OUTOFMEMORY;
        goto end;
    }

    slash = strrchr(base_dirA, '\\');
    if (slash)
        *(slash + 1) = 0;

    TRACE("setting base_dir: %s, config_path: %s\n", base_dirA, config_pathA);
    mono_domain_set_config(This->default_domain, base_dirA, config_pathA);

    HeapFree(GetProcessHeap(), 0, config_pathA);
    HeapFree(GetProcessHeap(), 0, base_dirA);

end:
    *result = This->default_domain;

    LeaveCriticalSection(&This->lock);

    return res;
}
예제 #29
0
/* Create an instance of a type given its name, by calling its constructor with
 * no arguments. Note that result MUST be in the stack, or the garbage
 * collector may free it prematurely. */
HRESULT RuntimeHost_CreateManagedInstance(RuntimeHost *This, LPCWSTR name,
    MonoDomain *domain, MonoObject **result)
{
    HRESULT hr=S_OK;
    char *nameA=NULL;
    MonoType *type;
    MonoClass *klass;
    MonoObject *obj;

    if (!domain)
        hr = RuntimeHost_GetDefaultDomain(This, &domain);

    if (SUCCEEDED(hr))
    {
        nameA = WtoA(name);
        if (!nameA)
            hr = E_OUTOFMEMORY;
    }

    if (SUCCEEDED(hr))
    {
        mono_thread_attach(domain);

        type = mono_reflection_type_from_name(nameA, NULL);
        if (!type)
        {
            ERR("Cannot find type %s\n", debugstr_w(name));
            hr = E_FAIL;
        }
    }

    if (SUCCEEDED(hr))
    {
        klass = mono_class_from_mono_type(type);
        if (!klass)
        {
            ERR("Cannot convert type %s to a class\n", debugstr_w(name));
            hr = E_FAIL;
        }
    }

    if (SUCCEEDED(hr))
    {
        obj = mono_object_new(domain, klass);
        if (!obj)
        {
            ERR("Cannot allocate object of type %s\n", debugstr_w(name));
            hr = E_FAIL;
        }
    }

    if (SUCCEEDED(hr))
    {
        /* FIXME: Detect exceptions from the constructor? */
        mono_runtime_object_init(obj);
        *result = obj;
    }

    HeapFree(GetProcessHeap(), 0, nameA);

    return hr;
}
예제 #30
0
BOOL CParseChText4::SaveChText(LPCWSTR filePath)
{
	wstring loadFilePath = L"";
	wstring loadTunerName = L"";
	if( filePath == NULL ){
		loadFilePath = this->filePath;
		loadTunerName = this->tunerName;
	}else{
		loadFilePath = filePath;
		wregex re(L".+\\\\(.+)\\(.+\\)\\.ChSet4\\.txt$");
		wstring text(filePath);
		wsmatch m;
		if( regex_search(text, m, re) ){ 
			loadTunerName = m[1];
			loadTunerName += L".dll";
		}
	}

	if( loadFilePath.size() == 0 ){
		return FALSE;
	}

	if( loadTunerName.size() == 0 ){
		return FALSE;
	}

	multimap<LONGLONG, CH_DATA4> sortList;
	multimap<LONGLONG, CH_DATA4>::iterator itr;
	for( itr = this->chList.begin(); itr != this->chList.end(); itr++ ){
		LONGLONG Key = ((LONGLONG)itr->second.space)<<32 | ((LONGLONG)itr->second.ch)<<16 | (LONGLONG)itr->second.serviceID;
		sortList.insert(pair<LONGLONG, CH_DATA4>(Key, itr->second));
	}


	// ファイル出力
	HANDLE hFile = _CreateFile2( loadFilePath.c_str(), GENERIC_WRITE, FILE_SHARE_READ, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
	if( hFile == INVALID_HANDLE_VALUE ){
		return FALSE;
	}

	for( itr = sortList.begin(); itr != sortList.end(); itr++ ){
		string chName="";
		WtoA(itr->second.chName, chName);
		string serviceName="";
		WtoA(itr->second.serviceName, serviceName);
		string networkName="";
		WtoA(itr->second.networkName, networkName);

		string strBuff;
		Format(strBuff, "%s\t%s\t%s\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\r\n",
			chName.c_str(),
			serviceName.c_str(),
			networkName.c_str(),
			itr->second.space,
			itr->second.ch,
			itr->second.originalNetworkID,
			itr->second.transportStreamID,
			itr->second.serviceID,
			itr->second.serviceType,
			itr->second.partialFlag,
			itr->second.useViewFlag,
			itr->second.remoconID
			);
		DWORD dwWrite = 0;
		WriteFile(hFile, strBuff.c_str(), (DWORD)strBuff.length(), &dwWrite, NULL);
	}

	CloseHandle(hFile);

	wstring appIniPath = L"";
	GetModuleIniPath(appIniPath);

	wstring ipString;
	DWORD ip;
	DWORD port;

	ip = GetPrivateProfileInt(L"SET_UDP", L"IP0", 2130706433, appIniPath.c_str());
	Format(ipString, L"%d.%d.%d.%d", 
	(ip&0xFF000000)>>24, 
	(ip&0x00FF0000)>>16, 
	(ip&0x0000FF00)>>8, 
	(ip&0x000000FF) );
	port = GetPrivateProfileInt( L"SET_UDP", L"Port0", 3456, appIniPath.c_str() );

	// MediaPortal TV Serverのデータベースへ登録
	if (this->dbCtrl.Connect(&this->mysql, MYSQL_HOST, MYSQL_USER, MYSQL_PASSWD, MYSQL_DB) != 0) {
		return FALSE;
	}

	this->results = NULL;
	CString sql = L"";
	wstring wsql = L"";
	int chkNum = 0;

	this->dbCtrl.Begin(&this->mysql);

	map<CString, int> lockTable;
	lockTable[L"channelgroup"] = 2;
	lockTable[L"tuningdetail"] = 2;
	lockTable[L"groupmap"    ] = 2;
	lockTable[L"channel"     ] = 2;
	lockTable[L"channelmap"  ] = 2;
	if (this->dbCtrl.LockTable(&this->mysql, lockTable) != 0) goto ESC;


	// channelgroupの登録が何個あるか調べる
	sql  = L"SELECT idGroup FROM channelgroup WHERE idGroup < 2;";
	if (this->dbCtrl.Query(&this->mysql, sql) != 0) goto ESC;
	this->dbCtrl.StoreResult(&this->mysql, &this->results);
	chkNum = this->dbCtrl.NumRows(&this->results);
	this->dbCtrl.FreeResult(&this->results);

	int maxNum;
	sql  = L"SELECT MAX(idGroup) FROM channelgroup;";
	if (this->dbCtrl.Query(&this->mysql, sql) != 0) goto ESC;
	this->dbCtrl.StoreResult(&this->mysql, &this->results);
	this->record = this->dbCtrl.FetchRow(&this->results);
	maxNum = atoi(this->record[0]);
	this->dbCtrl.FreeResult(&this->results);

	switch(chkNum){
		case 0: // 登録が0個ならidGroupの0(地上波・BS)と1(CS)を登録する
			// idGroupに0はオートナンバーのためINSERTの段階では登録できないのでINSERTしてから変更する
			sql.Format(_T("INSERT INTO channelgroup VALUES(%d,'地上波・BS',0);"), maxNum + 1);
			if (this->dbCtrl.Query(&this->mysql, sql) != 0) goto ESC;

			sql.Format(_T("UPDATE channelgroup SET idGroup = 0 WHERE idGroup = %d;"), maxNum + 1);
			if (this->dbCtrl.Query(&this->mysql, sql) != 0) goto ESC;

			sql  = L"INSERT INTO channelgroup VALUES(1,'CS',1);";
			if (this->dbCtrl.Query(&this->mysql, sql) != 0) goto ESC;
			break;
		case 1: // 登録が1個ならidGroupの1を末番に変更して、idGroupの0(地上波・BS)と1(CS)を登録する
			// 1個ということはMediaPortal_Bonより前にMediaPortal TV Serverのチャンネル設定で初期値が入った。
			sql.Format(_T("UPDATE channelgroup SET idGroup = %d WHERE idGroup = 1;"), maxNum + 1);
			if (this->dbCtrl.Query(&this->mysql, sql) != 0) goto ESC;

			sql.Format(_T("UPDATE groupmap SET idGroup = %d WHERE idGroup = 1;"), maxNum + 1);
			if (this->dbCtrl.Query(&this->mysql, sql) != 0) goto ESC;

			sql  = L"SELECT MAX(idGroup) FROM channelgroup;";
			if (this->dbCtrl.Query(&this->mysql, sql) != 0) goto ESC;
			this->dbCtrl.StoreResult(&this->mysql, &this->results);
			this->record = this->dbCtrl.FetchRow(&this->results);
			maxNum = atoi(this->record[0]);
			this->dbCtrl.FreeResult(&this->results);

			sql.Format(_T("INSERT INTO channelgroup VALUES(%d,'地上波・BS',0);"), maxNum + 1);
			if (this->dbCtrl.Query(&this->mysql, sql) != 0) goto ESC;

			sql.Format(_T("UPDATE channelgroup SET idGroup = 0 WHERE idGroup = %d;"), maxNum + 1);
			if (this->dbCtrl.Query(&this->mysql, sql) != 0) goto ESC;

			sql  = L"INSERT INTO channelgroup VALUES(1,'CS',1);";
			if (this->dbCtrl.Query(&this->mysql, sql) != 0) goto ESC;
			break;
	}

	// 同じチューナーの既存の登録に対してチューナー名を変更する。
	sql.Format(_T("UPDATE tuningdetail SET provider = '@_%s' WHERE provider = '%s';"), loadTunerName.c_str(), loadTunerName.c_str());
	if (this->dbCtrl.Query(&this->mysql, sql) != 0) goto ESC;

	//sql.Format(_T("iterator = '%d' '%d';"), sortList.begin(), sortList.end());
	//AfxMessageBox(sql, NULL, MB_OK);

	int tmpCh;  // 登録用チャンネル
	for( itr = sortList.begin(); itr != sortList.end(); itr++ ){
		if(itr->second.useViewFlag){
			wsql  = L"";
			wsql += L"SELECT idChannel FROM tuningdetail WHERE ";
			wsql += L"provider = '@_%s' AND ";
			wsql += L"channelNumber = %d AND ";
			wsql += L"networkId     = %d AND ";
			wsql += L"transportId   = %d AND ";
			wsql += L"serviceId     = %d;";
			sql.Format(wsql.c_str(),
				loadTunerName.c_str(),
				itr->second.ch,
				itr->second.originalNetworkID,
				itr->second.transportStreamID,
				itr->second.serviceID
				);
			if (this->dbCtrl.Query(&this->mysql, sql) != 0) goto ESC;
			this->dbCtrl.StoreResult(&this->mysql, &this->results);

			//AfxMessageBox(loadTunerName.c_str(), NULL, MB_OK);

			if(this->dbCtrl.NumRows(&this->results)){ // 既存のチャンネルは退避する
				this->record = this->dbCtrl.FetchRow(&this->results);
				tmpCh = atoi(this->record[0]);
				this->dbCtrl.FreeResult(&this->results);

				wsql  = L"";
				wsql += L"UPDATE tuningdetail SET provider = '%s' WHERE ";
				wsql += L"provider = '@_%s' AND ";
				wsql += L"channelNumber = %d AND ";
				wsql += L"networkId     = %d AND ";
				wsql += L"transportId   = %d AND ";
				wsql += L"serviceId     = %d;";
				sql.Format(wsql.c_str(),
					loadTunerName.c_str(),
					loadTunerName.c_str(),
					itr->second.ch,
					itr->second.originalNetworkID,
					itr->second.transportStreamID,
					itr->second.serviceID
					);
				if (this->dbCtrl.Query(&this->mysql, sql) != 0) goto ESC;

				// 既存のチャンネル登録があってもgroupmap.idGroupが適切な値(0:地上波・BS, 1:CS)になっているかを調べる。
				sql.Format(_T("SELECT idMap FROM groupmap WHERE idChannel = %d AND idGroup = %d;"), tmpCh, itr->second.space);
				if (this->dbCtrl.Query(&this->mysql, sql) != 0) goto ESC;
				this->dbCtrl.StoreResult(&this->mysql, &this->results);
				if(!this->dbCtrl.NumRows(&this->results)){
					this->dbCtrl.FreeResult(&this->results);
					sql  = L"SELECT SortOrder FROM groupmap;";
					if (this->dbCtrl.Query(&this->mysql, sql) != 0) goto ESC;
					this->dbCtrl.StoreResult(&this->mysql, &this->results);
					maxNum = this->dbCtrl.NumRows(&this->results);

					// groupmap.idGroupに適切な値(0:地上波・BS, 1:CS)の登録を行う。
					sql.Format(_T("INSERT INTO groupmap VALUES(0, %d, %d, %d);"), itr->second.space, tmpCh, maxNum);
					if (this->dbCtrl.Query(&this->mysql, sql) != 0) goto ESC;
				}
				this->dbCtrl.FreeResult(&this->results);

				// チャンネル概要があるか
				sql.Format(_T("SELECT displayName FROM channel WHERE idChannel = %d;"), tmpCh);
				if (this->dbCtrl.Query(&this->mysql, sql) != 0) goto ESC;
				this->dbCtrl.StoreResult(&this->mysql, &this->results);
				if(!this->dbCtrl.NumRows(&this->results)){
					// チャンネルの登録を行う。
					sql.Format(_T("INSERT INTO channel VALUES(%d,0,1,0,'2000-01-01 00:00:00',0,'2000-01-01 00:00:00',%d,1,'','%s',0,%d);"), 
						tmpCh, 
						(tmpCh + itr->second.space * 1000), 
						itr->second.serviceName.c_str(),
						itr->second.ch
					);
					if (this->dbCtrl.Query(&this->mysql, sql) != 0) goto ESC;
				}
				this->dbCtrl.FreeResult(&this->results);

				// チャンネルマップがあるか
				sql.Format(_T("SELECT idChannelMap FROM channelmap WHERE idChannel = %d AND idCard = 1;"), tmpCh);
				if (this->dbCtrl.Query(&this->mysql, sql) != 0) goto ESC;
				this->dbCtrl.StoreResult(&this->mysql, &this->results);
				if(!this->dbCtrl.NumRows(&this->results)){
					// チャンネルマップの登録を行う。
					sql.Format(_T("INSERT INTO channelmap VALUES(0,%d,1,0);"), tmpCh);
					if (this->dbCtrl.Query(&this->mysql, sql) != 0) goto ESC;
				}
				this->dbCtrl.FreeResult(&this->results);

			} else { // チャンネルを新規登録
				this->dbCtrl.FreeResult(&this->results);

				// BONドライバーが違っても同じチャンネルがあるかどうか
				wsql  = L"";
				wsql += L"SELECT idChannel FROM tuningdetail WHERE ";
				wsql += L"provider <> '@_%s' AND ";
				wsql += L"channelNumber = %d AND ";
				wsql += L"networkId     = %d AND ";
				wsql += L"transportId   = %d AND ";
				wsql += L"serviceId     = %d;";
				sql.Format(wsql.c_str(),
					loadTunerName.c_str(),
					itr->second.ch,
					itr->second.originalNetworkID,
					itr->second.transportStreamID,
					itr->second.serviceID
					);
				if (this->dbCtrl.Query(&this->mysql, sql) != 0) goto ESC;
				this->dbCtrl.StoreResult(&this->mysql, &this->results);
				
				// 同じチャンネルがある場合はそのチャンネルを使う
				// ない場合はチャンネル概要の次番号を得る。
				if(!this->dbCtrl.NumRows(&this->results)){
					sql  = L"SELECT MAX(idChannel) FROM channel;";
					if (this->dbCtrl.Query(&this->mysql, sql) != 0) goto ESC;
					this->dbCtrl.StoreResult(&this->mysql, &this->results);
				}
				this->record = this->dbCtrl.FetchRow(&this->results);
				//if(CA2T(this->record[0], CP_UTF8) == L"") maxNum = 0;
				if(this->record[0] == 0x00000000) maxNum = 0;
				else maxNum = atoi(this->record[0]);
				tmpCh  = maxNum + 1;
				this->dbCtrl.FreeResult(&this->results);

				// チャンネル概要があるか
				sql.Format(_T("SELECT displayName FROM channel WHERE idChannel = %d;"), tmpCh);
				if (this->dbCtrl.Query(&this->mysql, sql) != 0) goto ESC;
				this->dbCtrl.StoreResult(&this->mysql, &this->results);
				if(!this->dbCtrl.NumRows(&this->results)){
					// チャンネルの登録を行う。
					sql.Format(_T("INSERT INTO channel VALUES(%d,0,1,0,'2000-01-01 00:00:00',0,'2000-01-01 00:00:00',%d,1,'','%s',0,%d);"), 
						tmpCh, 
						(tmpCh + itr->second.space * 1000), 
						itr->second.serviceName.c_str(),
						itr->second.ch
					);
					if (this->dbCtrl.Query(&this->mysql, sql) != 0) goto ESC;
				}
				this->dbCtrl.FreeResult(&this->results);

				// チャンネル詳細の次番号を得る。
				int maxTuNum;
				sql  = L"SELECT MAX(idTuning) FROM tuningdetail;";
				if (this->dbCtrl.Query(&this->mysql, sql) != 0) goto ESC;
				this->dbCtrl.StoreResult(&this->mysql, &this->results);
				this->record = this->dbCtrl.FetchRow(&this->results);
				if(this->record[0] == 0x00000000) maxTuNum = 0;
				else maxTuNum = atoi(this->record[0]);
				this->dbCtrl.FreeResult(&this->results);

				// チャンネル詳細登録
				sql.Format(L"INSERT INTO tuningdetail VALUES(%d,%d,'%s','%s',7,%d,0,31,0,1,%d,%d,%d,496,0,0,0,0,1,0,8,-1,-1,0,0,0,-1,-1,-1,-1,'udp://%s:%d',0,0,0);",
					maxTuNum + 1,
					tmpCh,
					itr->second.serviceName.c_str(),
					loadTunerName.c_str(),
					itr->second.ch,
					itr->second.originalNetworkID,
					itr->second.transportStreamID,
					itr->second.serviceID,
					ipString.c_str(),
					port
				);
				if (this->dbCtrl.Query(&this->mysql, sql) != 0) goto ESC;

				//AfxMessageBox(sql, NULL, MB_OK);

				// グループがあるか
				sql.Format(_T("SELECT idChannel FROM groupmap WHERE idGroup = %d AND idChannel = %d;"), itr->second.space, tmpCh);
				if (this->dbCtrl.Query(&this->mysql, sql) != 0) goto ESC;
				this->dbCtrl.StoreResult(&this->mysql, &this->results);
				if(!this->dbCtrl.NumRows(&this->results)){
					this->dbCtrl.FreeResult(&this->results);
					sql  = L"SELECT SortOrder FROM groupmap;";
					if (this->dbCtrl.Query(&this->mysql, sql) != 0) goto ESC;
					this->dbCtrl.StoreResult(&this->mysql, &this->results);
					maxNum = this->dbCtrl.NumRows(&this->results);

					// グループの登録を行う。
					sql.Format(_T("INSERT INTO groupmap VALUES(0, %d, %d, %d);"), itr->second.space, tmpCh, maxNum);
					if (this->dbCtrl.Query(&this->mysql, sql) != 0) goto ESC;
				}
				this->dbCtrl.FreeResult(&this->results);
				
				// チャンネルマップがあるか
				sql.Format(_T("SELECT idChannelMap FROM channelmap WHERE idChannel = %d AND idCard = 2;"), tmpCh);
				if (this->dbCtrl.Query(&this->mysql, sql) != 0) goto ESC;
				this->dbCtrl.StoreResult(&this->mysql, &this->results);
				if(!this->dbCtrl.NumRows(&this->results)){
					// チャンネルマップの登録を行う。
					sql.Format(_T("INSERT INTO channelmap VALUES(0,%d,2,0);"), tmpCh);
					if (this->dbCtrl.Query(&this->mysql, sql) != 0) goto ESC;
				}
				this->dbCtrl.FreeResult(&this->results);
			}
		}
	}

	// 残ったチャンネルを削除する
	sql.Format(_T("DELETE FROM tuningdetail WHERE provider = '@_%s';"), loadTunerName.c_str());
	if (this->dbCtrl.Query(&this->mysql, sql) != 0) goto ESC;

	// ついでにチューナーのないチャンネルを削除する
	sql  = L"DELETE channel FROM channel LEFT JOIN tuningdetail ON channel.idChannel = tuningdetail.idChannel WHERE tuningdetail.idChannel IS NULL;";
	if (this->dbCtrl.Query(&this->mysql, sql) != 0) goto ESC;

	// ついでにチャンネルのないグループを削除する。
	sql  = L"DELETE groupmap FROM groupmap LEFT JOIN channel ON groupmap.idChannel = channel.idChannel WHERE channel.idChannel IS NULL;";
	if (this->dbCtrl.Query(&this->mysql, sql) != 0) goto ESC;

	// ついでにチャンネルのないチャンネルマップも削除する
	sql  = L"DELETE channelmap FROM channelmap LEFT JOIN channel ON channelmap.idChannel = channel.idChannel WHERE channel.idChannel IS NULL;";
	if (this->dbCtrl.Query(&this->mysql, sql) != 0) goto ESC;

	this->dbCtrl.Commit(&this->mysql);
	this->dbCtrl.UnlockTable(&this->mysql);
	this->dbCtrl.Close(&this->mysql);
	return TRUE;

	ESC: 
	wstring err = L"";
	Format(err, L"ERROR SQL:%s", sql);
	AfxMessageBox(err.c_str(), NULL, MB_OK);
	this->dbCtrl.Rollback(&this->mysql);
	this->dbCtrl.UnlockTable(&this->mysql);
	this->dbCtrl.Close(&this->mysql);
	return FALSE;
}