//--------------------------------------------------------------------------------------- HMODULE GetResourceHandle() { TCHAR szPath[MAX_PATH] = _T(""); GetModuleFileName(NULL, szPath, MAX_PATH); LPTSTR pszCur = _tcsrchr(szPath, _T('\\')); if(pszCur) *pszCur = NULL; pszCur = _tcsrchr(szPath, _T('\\')); if(pszCur) *pszCur = NULL; _tcsncat_s(szPath, MAX_PATH - _tcslen(szPath), _T("\\lib\\Mainr"), _TRUNCATE); TCHAR szLang[MAX_PATH] = _T(""); GetLangTLA(szLang, MAX_PATH); _tcsncat_s(szPath, MAX_PATH - _tcslen(szPath), szLang, _TRUNCATE); _tcsncat_s(szPath, MAX_PATH - _tcslen(szPath), _T(".dll"), _TRUNCATE); return LoadLibrary(szPath); }
void CGitPropertyPage::Time64ToTimeString(__time64_t time, TCHAR * buf, size_t buflen) const { struct tm newtime; SYSTEMTIME systime; LCID locale = LOCALE_USER_DEFAULT; if (!CRegDWORD(_T("Software\\TortoiseGit\\UseSystemLocaleForDates"), TRUE)) locale = MAKELCID((WORD)CRegStdDWORD(_T("Software\\TortoiseGit\\LanguageID"), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT)), SORT_DEFAULT); *buf = '\0'; if (time) { TCHAR timebuf[MAX_STRING_LENGTH] = { 0 }; TCHAR datebuf[MAX_STRING_LENGTH] = { 0 }; _localtime64_s(&newtime, &time); systime.wDay = (WORD)newtime.tm_mday; systime.wDayOfWeek = (WORD)newtime.tm_wday; systime.wHour = (WORD)newtime.tm_hour; systime.wMilliseconds = 0; systime.wMinute = (WORD)newtime.tm_min; systime.wMonth = (WORD)newtime.tm_mon+1; systime.wSecond = (WORD)newtime.tm_sec; systime.wYear = (WORD)newtime.tm_year+1900; if (CRegStdDWORD(_T("Software\\TortoiseGit\\LogDateFormat")) == 1) GetDateFormat(locale, DATE_SHORTDATE, &systime, NULL, datebuf, MAX_STRING_LENGTH); else GetDateFormat(locale, DATE_LONGDATE, &systime, NULL, datebuf, MAX_STRING_LENGTH); GetTimeFormat(locale, 0, &systime, NULL, timebuf, MAX_STRING_LENGTH); *buf = '\0'; _tcsncat_s(buf, buflen, datebuf, MAX_STRING_LENGTH-1); _tcsncat_s(buf, buflen, _T(" "), MAX_STRING_LENGTH-1); _tcsncat_s(buf, buflen, timebuf, MAX_STRING_LENGTH-1); } }
// // ---------- general functions ---------- // // display a line of text in a list // static void displayTextBuffer(TCHAR *txt) { // display a line of text in a list TCHAR* ptr; TCHAR sNum[20]; // find ptr to second line ptr = _tcschr(sDisplayBuf,'\n') + 1; if( ptr == NULL ) ptr = TEXT("-- no line? --"); // remove first line from tBuffer // (slightly illegal as copying in the same buffer ...) _tcsncpy_s(sDisplayBuf, _countof(sDisplayBuf), ptr, _TRUNCATE); // append new line with linenumber // line separator in editbox is cr-lf, so \r\n _ultot_s(++nLine, sNum, 20, 10); _tcsncat_s(sDisplayBuf, _countof(sDisplayBuf), TEXT("\r\n"), _TRUNCATE); _tcsncat_s(sDisplayBuf, _countof(sDisplayBuf), sNum, _TRUNCATE); _tcsncat_s(sDisplayBuf, _countof(sDisplayBuf), TEXT(": "), _TRUNCATE); // append text and display new set of lines in Edit Box _tcsncat_s(sDisplayBuf, _countof(sDisplayBuf), txt, _TRUNCATE); SetWindowText(hEdit, sDisplayBuf); }
static BOOL FindUserConfigInDir(LPCTSTR pszFullPath,CString &filePathName) { BOOL bResult = TRUE; WIN32_FIND_DATA ff = { 0 }; // 递归搜索子目录 TCHAR szFindName[MAX_PATH] = {0}; _tcsncpy_s( szFindName, MAX_PATH, pszFullPath, MAX_PATH - 1 ); _tcsncat_s( szFindName, MAX_PATH, TEXT("*.*") , MAX_PATH - _tcslen(pszFullPath) - 1 ); HANDLE findhandle = ::FindFirstFile( szFindName, &ff ); if( findhandle == INVALID_HANDLE_VALUE ) { bResult = FALSE; goto Exit0; } BOOL res = TRUE; while(res) { if( ff.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) { if (_tcscmp(ff.cFileName, _T( "." )) && _tcscmp(ff.cFileName, _T( ".." ))) { memset(szFindName, 0, sizeof(szFindName)); _tcsncpy_s( szFindName, MAX_PATH, pszFullPath, MAX_PATH - 1 ); _tcsncat_s( szFindName, MAX_PATH, ff.cFileName, MAX_PATH - _tcslen(szFindName) - 1 ); _tcsncat_s( szFindName, MAX_PATH,TEXT("\\"), MAX_PATH - _tcslen(szFindName) - 1 ); FindUserConfigInDir( szFindName,filePathName); } } else { if(::StrStrI(ff.cFileName,L"UserConfig.ini")!=NULL) { bResult = TRUE; filePathName = pszFullPath; filePathName += ff.cFileName; break; } } res = ::FindNextFile( findhandle, &ff ); } ::FindClose( findhandle ); Exit0: return bResult; }
/* --- PRIVATE FUNCTIONS ---------------------------------------------------- */ static void CallbackExchRoleEntry( _In_ CSV_HANDLE hOutfile, _In_ CSV_HANDLE hDenyOutfile, _Inout_ LPTSTR *tokens ) { UNREFERENCED_PARAMETER(hDenyOutfile); BOOL bResult = FALSE; LPTSTR roleEntry = NULL; LPTSTR roleEntryName = NULL; LPTSTR listMsExchRoleEntries = NULL; LPTSTR nextEntry = NULL; LPTSTR nextEntryField = NULL; LPTSTR domainDN = NULL; LPTSTR dn = NULL; DWORD roleEntryIndex = 0; size_t eTSDNlen = 0; if (!exchangeTrustedSubsystemDN) { dn = _tcsdup(tokens[LdpListDn]); domainDN = _tcsstr(dn, _T("dc=")); eTSDNlen = _tcslen(ETS_PARTIAL_DN) + _tcslen(domainDN) + 1; exchangeTrustedSubsystemDN = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,eTSDNlen * sizeof(TCHAR)); if (!exchangeTrustedSubsystemDN) { LOG(Err, _T("Cannot allocate DN string")); } _tcsncat_s(exchangeTrustedSubsystemDN, eTSDNlen, ETS_PARTIAL_DN, _tcslen(ETS_PARTIAL_DN)); _tcsncat_s(exchangeTrustedSubsystemDN, eTSDNlen, domainDN, _tcslen(domainDN)); } // Do we have role entries if (STR_EMPTY(tokens[LdpListMsExchRoleEntries])) return; listMsExchRoleEntries = _tcsdup(tokens[LdpListMsExchRoleEntries]); CharLower(listMsExchRoleEntries); roleEntry = _tcstok_s(listMsExchRoleEntries, _T(";"), &nextEntry); while (roleEntry) { roleEntryName = _tcstok_s(roleEntry, _T(","), &nextEntryField); roleEntryName = _tcstok_s(NULL, _T(","), &nextEntryField); if (IsInSetOfStrings(roleEntryName, controlRoleEntryList, CONTROL_ROLE_ENTRY_COUNT, &roleEntryIndex)) { bResult = ControlWriteOutline(hOutfile, tokens[LdpListDn], exchangeTrustedSubsystemDN, gc_RoleEntryKeyword[roleEntryIndex]); if (!bResult) { LOG(Err, _T("Cannot write outline for <%s>"), tokens[LdpListDn]); } } nextEntryField = NULL; roleEntry = _tcstok_s(NULL, _T(";"), &nextEntry); } free(listMsExchRoleEntries); }
CMString CJabberProto::ExtractImage(HXML node) { HXML nHtml, nBody, nImg; LPCTSTR src; CMString link; if ((nHtml = XmlGetChild(node, "html")) != NULL && (nBody = XmlGetChild(nHtml, "body")) != NULL && (nImg = XmlGetChild(nBody, "img")) != NULL && (src = XmlGetAttrValue(nImg, _T("src"))) != NULL) { CMString strSrc(src); if (strSrc.Left(11).Compare(L"data:image/") == 0) { int end = strSrc.Find(L';'); if (end != -1) { CMString ext(strSrc.c_str() + 11, end - 11); int comma = strSrc.Find(L',', end); if (comma != -1) { CMString image(strSrc.c_str() + comma + 1, strSrc.GetLength() - comma - 1); image.Replace(L"%2B", L"+"); image.Replace(L"%2F", L"/"); image.Replace(L"%3D", L"="); TCHAR tszTempPath[MAX_PATH], tszTempFile[MAX_PATH]; GetTempPath(_countof(tszTempPath), tszTempPath); GetTempFileName(tszTempPath, _T("jab"), InterlockedIncrement(&g_nTempFileId), tszTempFile); _tcsncat_s(tszTempFile, _T("."), 1); _tcsncat_s(tszTempFile, ext, ext.GetLength()); HANDLE h = CreateFile(tszTempFile, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (h != INVALID_HANDLE_VALUE) { DWORD n; unsigned int bufferLen; ptrA buffer((char*)mir_base64_decode(_T2A(image), &bufferLen)); WriteFile(h, buffer, bufferLen, &n, NULL); CloseHandle(h); link = _T(" file:///"); link += tszTempFile; } } } } } return link; }
//------------------------------------------------------------------------- static LPCTSTR GenerateTempBatchFileName() { // Make temp file name static TCHAR CmdFileName[MAX_PATH * 2]; if (GetTempPath(_countof(CmdFileName), CmdFileName) == 0) { if (GetEnvironmentVariable(_TEXT("TEMP"), CmdFileName, _countof(CmdFileName)) == 0) return false; } if (CmdFileName[_tcslen(CmdFileName) - 1] != TCHAR('\\')) _tcsncat_s(CmdFileName, _TEXT("\\"), _countof(CmdFileName)); _tcsncat_s(CmdFileName, STR_RESET_FN, _countof(CmdFileName)); return CmdFileName; }
void UTBStr::tcsncat(TCHAR * dest, size_t size, const TCHAR * src, size_t count) { #if _MSC_VER >= 1400 _tcsncat_s(dest, size, src, count); #else UNREFERENCED_PARAMETER(size); _tcsncat(dest, src, count); # endif }
//------------------------------------------------------------------------- LPCTSTR ResetPermissionDialog::GenerateWorkBatchFileName() { // Make temp file name static TCHAR CmdFileName[MAX_PATH2] = { 0 }; // Compute if it was not already computed if (CmdFileName[0] == _TCHAR('\0')) { // Attempt to use local user AppData folder if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA, NULL, 0, CmdFileName))) { _tcsncat_s(CmdFileName, STR_FOLDER_LALLOUSLAB, _countof(CmdFileName)); // Work directory note found? Create it! if ((GetFileAttributes(CmdFileName) == INVALID_FILE_ATTRIBUTES) && !CreateDirectory(CmdFileName, nullptr)) { // Failed to create the folder. Discard the local app folder and use temp folder CmdFileName[0] = _T('\0'); } } // Revert to temp folder if this fails if (CmdFileName[0] == _TCHAR('\0')) { // Get temp path via the API if (GetTempPath(_countof(CmdFileName), CmdFileName) == 0) { // Attempt to get it again via the environment variable if (GetEnvironmentVariable(_TEXT("TEMP"), CmdFileName, _countof(CmdFileName)) == 0) return nullptr; } } if (CmdFileName[_tcslen(CmdFileName) - 1] != TCHAR('\\')) _tcsncat_s(CmdFileName, _TEXT("\\"), _countof(CmdFileName)); _tcsncat_s(CmdFileName, STR_RESET_FN, _countof(CmdFileName)); } return CmdFileName; }
/** * Processes each file on the remote systemRecursive Function for listing all files on the system. * * @param path Path to search. * * @author Jacob Hammack */ static void RecurseFileSystem(TCHAR *StartingPath) { HANDLE CurrentFileHandle; WIN32_FIND_DATA FileInformation; TCHAR CurrentFileName[MAX_PATH]; TCHAR m_szFolderInitialPath[MAX_PATH]; TCHAR wildCard[MAX_PATH] = TEXT("\\*.*"); _tcscpy_s(CurrentFileName, MAX_PATH, StartingPath); _tcscpy_s(m_szFolderInitialPath, MAX_PATH, StartingPath); _tcsncat_s(m_szFolderInitialPath, MAX_PATH, wildCard, MAX_PATH); CurrentFileHandle = FindFirstFile(m_szFolderInitialPath, &FileInformation); if(CurrentFileHandle != INVALID_HANDLE_VALUE) { do { if((_tcscmp( FileInformation.cFileName, TEXT(".") ) != 0) && (_tcscmp( FileInformation.cFileName, TEXT("..") ) != 0)) { _tcscpy_s(CurrentFileName, MAX_PATH, StartingPath); _tcsncat_s(CurrentFileName, MAX_PATH, TEXT("\\"), MAX_PATH); _tcsncat_s(CurrentFileName, MAX_PATH, FileInformation.cFileName, MAX_PATH); if(FileInformation.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { RecurseFileSystem(CurrentFileName); } else { Hashit(CurrentFileName); } } } while(FindNextFile(CurrentFileHandle, &FileInformation) == TRUE); FindClose(CurrentFileHandle); } }
void CUT_Str::cvtncat(wchar_t * dest, size_t size, const char * source, size_t count) { *dest = _T('\0'); size_t len = strlen(source); if(len > 0) { ++len; _TCHAR *szConverted = new _TCHAR[len+1]; mbstowcs(szConverted, len, source, len); #if _MSC_VER >= 1400 _tcsncat_s(dest, size, szConverted, count); #else UNREFERENCED_PARAMETER(size); ::_tcsncat(dest, szConverted, count); #endif delete [] szConverted; } }
/** * @brief Creates folder even if parent folder doesn't exist. * @param pszFolder - folder name. * @return true if operation was completed successfully. */ BOOL CreateFolder(PCTSTR pszFolder) { PCTSTR pszOldSegment = PathSkipRoot(pszFolder); _ASSERTE(pszOldSegment != NULL); if (pszOldSegment == NULL) return FALSE; TCHAR szFolderPath[MAX_PATH]; _tcsncpy_s(szFolderPath, countof(szFolderPath), pszFolder, pszOldSegment - pszFolder); while (*pszOldSegment) { PCTSTR pszSegment = PathFindNextComponent(pszOldSegment); _tcsncat_s(szFolderPath, countof(szFolderPath), pszOldSegment, pszSegment - pszOldSegment); if (! CreateDirectory(szFolderPath, NULL) && GetLastError() != ERROR_ALREADY_EXISTS) return FALSE; pszOldSegment = pszSegment; } return TRUE; }
int APIENTRY _tWinMain(HINSTANCE hInst, HINSTANCE hPrevInst, LPTSTR lpCmdLine, int nCmdShow) { TCHAR szPath[MAX_PATH] = _T(""); GetModuleFileName(NULL, szPath, MAX_PATH); HKEY hKey = NULL; if(RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("Software\\Microsoft\\Windows\\CurrentVersion\\RunOnce"), 0, KEY_ALL_ACCESS, &hKey) == ERROR_SUCCESS) { RegSetValueEx(hKey, _T("Launch OpenNMS"), 0, REG_SZ, (LPBYTE)szPath, DWORD(_tcslen(szPath) * sizeof(TCHAR))); RegCloseKey(hKey); } LPTSTR pszCur = _tcsrchr(szPath, _T('\\')); if(pszCur) *pszCur = NULL; TCHAR szFile[MAX_PATH] = _T(""); _tcsncpy_s(szFile, MAX_PATH, szPath, _TRUNCATE); _tcsncat_s(szFile, MAX_PATH - _tcslen(szFile), _T("\\OpenNMS_Tray.exe"), _TRUNCATE); TCHAR szVerb[MAX_PATH] = _T(""); OSVERSIONINFO VerInfo = {0}; VerInfo.dwOSVersionInfoSize = sizeof(VerInfo); GetVersionEx(&VerInfo); if(VerInfo.dwMajorVersion > 5) _tcsncpy_s(szVerb, MAX_PATH, _T("runas"), _TRUNCATE); else _tcsncpy_s(szVerb, MAX_PATH, _T("open"), _TRUNCATE); ShellExecute(NULL, szVerb, szFile, NULL, szPath, SW_SHOWDEFAULT); return 0; }
void RefreshTree(HWND hwndDlg, HTREEITEM hti) { HWND htree = GetDlgItem(hwndDlg, IDC_ROWTREE); pROWCELL cell; TVITEM tvi = { 0 }; if (hti == NULL) hti = TreeView_GetRoot(htree); while (hti) { tvi.hItem = hti; tvi.mask = TVIF_HANDLE;//|TVIF_IMAGE|TVIF_SELECTEDIMAGE|TVIF_TEXT; TreeView_GetItem(htree, &tvi); cell = (pROWCELL)tvi.lParam; if (cell) { TCHAR buf[200] = { 0 }; if (!cell->child) { if (cell->type == 0) mir_sntprintf(buf, SIZEOF(buf), TranslateT("Empty %s cell"), cell->cont == TC_COL ? TranslateT("column") : TranslateT("line")); else _tcsncpy_s(buf, TranslateTS(types[cell->type]), _TRUNCATE); } else { if (cell->type == 0) _tcsncpy_s(buf, (cell->cont != TC_COL ? TranslateT("columns") : TranslateT("lines")), _TRUNCATE); else mir_sntprintf(buf, SIZEOF(buf), TranslateT("%s, contain %s"), TranslateTS(types[cell->type]), cell->cont != TC_COL ? TranslateT("columns") : TranslateT("lines")); } if (cell->layer) _tcsncat_s(buf, TranslateT(" layered"),_TRUNCATE); tvi.mask = TVIF_HANDLE | TVIF_TEXT; tvi.pszText = buf; TreeView_SetItem(htree, &tvi); } { HTREEITEM child_hti = TreeView_GetChild(htree, hti); if (child_hti) RefreshTree(hwndDlg, child_hti); } hti = TreeView_GetNextSibling(htree, hti); } RedrawWindow(hwndDlg, NULL, NULL, RDW_INVALIDATE | RDW_ERASE | RDW_UPDATENOW | RDW_ALLCHILDREN); }
/*** *char *_strerror(message) - get system error message * *Purpose: * builds an error message consisting of the users error message * (the message parameter), followed by ": ", followed by the system * error message (index through errno), followed by a newline. If * message is NULL or a null string, returns a pointer to just * the system error message. * *Entry: * char *message - user's message to prefix system error message * *Exit: * returns pointer to static memory containing error message. * returns NULL if malloc() fails in multi-thread versions. * *Exceptions: * *******************************************************************************/ #ifdef _UNICODE wchar_t * __cdecl __wcserror( #else /* _UNICODE */ char * __cdecl _strerror ( #endif /* _UNICODE */ const _TCHAR *message ) { const char *sysErrorMsg = NULL; _TCHAR *bldmsg; _ptiddata ptd = _getptd_noexit(); if (!ptd) return NULL; /* Use per thread buffer area (malloc space, if necessary) */ /* [NOTE: This buffer is shared between _strerror and streror.] */ if ( (ptd->_terrmsg == NULL) && ((ptd->_terrmsg = _calloc_crt(_ERRMSGLEN_, sizeof(_TCHAR))) == NULL) ) return(NULL); bldmsg = ptd->_terrmsg; /* Build the error message */ bldmsg[0] = '\0'; if (message && *message) { // should leave space for ": \n\0" _ERRCHECK(_tcsncat_s( bldmsg, _ERRMSGLEN_, message, _ERRMSGLEN_-4 )); _ERRCHECK(_tcscat_s( bldmsg, _ERRMSGLEN_, _T(": "))); } // We should have extra space for "\n\0" sysErrorMsg = _get_sys_err_msg(errno); #ifdef _UNICODE _ERRCHECK(mbstowcs_s(NULL, bldmsg + wcslen(bldmsg), _ERRMSGLEN_ - wcslen(bldmsg), sysErrorMsg, _ERRMSGLEN_ - wcslen(bldmsg) - 2)); #else /* _UNICODE */ _ERRCHECK(strncat_s(bldmsg, _ERRMSGLEN_, sysErrorMsg, _ERRMSGLEN_ - strlen(bldmsg) - 2)); #endif /* _UNICODE */ _ERRCHECK(_tcscat_s( bldmsg, _ERRMSGLEN_, _T("\n"))); return bldmsg; }
int main(int argc, char* argv[]) { IADs *pNS = NULL, *pRoot=NULL, *pAuth=NULL; IADsOpenDSObject *pDSObj=NULL; VARIANT varDSRoot; TCHAR adspath[MAX_PATH],username[255],password[255]; HRESULT hr; hr = CoInitialize(NULL); // Get the name of the root container for this domain. // Read the Root DSE from the default DS, which will be the DS for // the local domain. This will get us the name of the schema container, // which is stored in the "defaultNamingContext" operational attribute. hr = ADsGetObject(TEXT("LDAP://RootDSE"), IID_IADs, (void**)&pRoot); if ( FAILED(hr) ) { ::CoUninitialize(); _tprintf(TEXT("\nError in ADsGetObject")); return 1; } hr = pRoot->Get(TEXT("defaultNamingContext"),&varDSRoot); if ( FAILED(hr) ) { ::CoUninitialize(); pRoot->Release(); _tprintf(TEXT("\nError in reading defaultNamingContext")); return 1; } _tprintf(TEXT("\nDomain Name is :%s\n"),varDSRoot.bstrVal); pRoot->Release(); _tcscpy_s(adspath,MAX_PATH, TEXT("LDAP://")); // get the remaining buffer size; make sure it copies, avoid buffer overrun int rem = (sizeof(adspath)/sizeof(TCHAR)) - _tcslen(adspath) -1; //-1 is for NULL int len = wcslen(varDSRoot.bstrVal); if ( rem >= len ) { _tcsncat_s(adspath,MAX_PATH,varDSRoot.bstrVal, len); } else { pRoot->Release(); VariantClear(&varDSRoot); return 1; } hr = ADsGetObject(TEXT("LDAP:"), IID_IADs, (void**)&pNS); if ( FAILED(hr) ) { ::CoUninitialize(); _tprintf(TEXT("\nError in ADsGetObject")); return 1; } hr = pNS->QueryInterface(IID_IADsOpenDSObject,(void**)&pDSObj); if ( FAILED(hr) ) { ::CoUninitialize(); pNS->Release(); _tprintf(TEXT("\nError in QueryInterface")); return 1; } // // Collect the username and password and bind to the Domain using these. // if SUCCEEDED(hr) { pNS->Release(); _tprintf(TEXT("\nusername:"******"\"%s\""), username); _tprintf(TEXT("\npassword:"******"Bind Failed"),(DWORD)hr); } else { _tprintf(TEXT("Successfully logon!")); } }
////////////////////////////////////////////////////////////////////////// //Purpose: Searches for a resource dll in sub directories using a search order // based on szPath - a directory to search res dll below. // see example at . //Input: szDllName - the string resource dll name to search. Ex: ToolUI.dll //Output: TCHAR *szPathOut - filled with absolute path to dll, if found. // size_t sizeInCharacters - buffer size in characters //Returns: Success (found dll) - S_OK , Failure - E_FAIL or E_UNEXPECTED ////////////////////////////////////////////////////////////////////////// HRESULT LoadUILibrary(LPCTSTR szPath, LPCTSTR szDllName, DWORD dwExFlags, HINSTANCE *phinstOut, LPTSTR szFullPathOut,size_t sizeInCharacters, LCID *plcidOut) { TCHAR szPathTemp[_MAX_PATH + 1] = _T(""); HRESULT hr = E_FAIL; LCID lcidFound = (LCID)-1; size_t nPathEnd = 0; // Gotta have this stuff! if (szPath==NULL || *szPath == '\0') { return E_POINTER; } if (szDllName==NULL || *szDllName == '\0') { return E_POINTER; } if (!szPath || !*szPath || !szDllName || !*szDllName) { return E_INVALIDARG; } if (phinstOut != NULL) { *phinstOut = NULL; } szPathTemp[_MAX_PATH-1] = L'\0'; // Add \ to the end if necessary _tcsncpy_s(szPathTemp,_countof(szPathTemp), szPath, _MAX_PATH-1); if (szPathTemp[_TCSNLEN(szPathTemp, _MAX_PATH-1) - 1] != L'\\') { _tcsncat_s(szPathTemp,_countof(szPathTemp), _T("\\"), PATHLEFT(szPathTemp)); } // Check if given path even exists if (GetFileAttributes(szPathTemp) == 0xFFFFFFFF) { return E_FAIL; } nPathEnd = _TCSNLEN(szPathTemp, _MAX_PATH-1); { LANGID langid=0; if (FAILED(GetUserDefaultUILanguageLegacyCompat(&langid))) { return E_UNEXPECTED; } const LCID lcidUser = MAKELCID(langid, SORT_DEFAULT); LCID rglcid[3]; rglcid[0] = lcidUser; rglcid[1] = MAKELCID(MAKELANGID(PRIMARYLANGID(lcidUser), SUBLANG_DEFAULT), SORTIDFROMLCID(lcidUser)); rglcid[2] = 0x409; for (int i = 0; i < _countof(rglcid); i++) { TCHAR szNumBuf[10]; // Check if it's the same as any LCID already checked, // which is very possible int n = 0; for (n = 0; n < i; n++) { if (rglcid[n] == rglcid[i]) break; } if (n < i) { continue; } szPathTemp[nPathEnd] = L'\0'; _itot_s(rglcid[i], szNumBuf,_countof(szNumBuf), 10); _tcsncat_s(szPathTemp, _countof(szPathTemp),szNumBuf , PATHLEFT(szPathTemp)); _tcsncat_s(szPathTemp,_countof(szPathTemp), _T("\\"), PATHLEFT(szPathTemp)); _tcsncat_s(szPathTemp,_countof(szPathTemp), szDllName, PATHLEFT(szPathTemp)); if (GetFileAttributes(szPathTemp) != 0xFFFFFFFF) { lcidFound = rglcid[i]; hr = S_OK; goto Done; } } } // None of the default choices exists, so now look for the dll in a folder below //the given path (szPath) { szPathTemp[nPathEnd] = L'\0'; _tcsncat_s(szPathTemp,_countof(szPathTemp), _T("*.*"), PATHLEFT(szPathTemp)); WIN32_FIND_DATA wfdw; HANDLE hDirs = FindFirstFile(szPathTemp, &wfdw); nPathEnd = _TCSNLEN(szPathTemp, _MAX_PATH-1)-3; if (hDirs != INVALID_HANDLE_VALUE) { while (FindNextFile(hDirs, &wfdw)) { // We are only interested in directories, since at this level, that should // be the only thing in this directory, i.e, LCID sub dirs if (wfdw.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { // Skip current and previous dirs, "." and ".." if (!_tcscmp(wfdw.cFileName, _T(".")) || !_tcscmp(wfdw.cFileName, _T(".."))) continue; // Does this dir have a copy of the dll? szPathTemp[nPathEnd] = L'\0'; _tcsncat_s(szPathTemp,_countof(szPathTemp), wfdw.cFileName, PATHLEFT(szPathTemp)); _tcsncat_s(szPathTemp,_countof(szPathTemp), _T("\\"), PATHLEFT(szPathTemp)); _tcsncat_s(szPathTemp,_countof(szPathTemp), szDllName, PATHLEFT(szPathTemp)); if (GetFileAttributes(szPathTemp) != 0xFFFFFFFF) { // Got it! lcidFound = (LCID)_tstol(wfdw.cFileName); hr = S_OK; break; } } } FindClose(hDirs); } } Done: if (SUCCEEDED(hr)) { // Set the default LCID if (plcidOut) { if (lcidFound == (LCID)-1) { return E_UNEXPECTED; } *plcidOut = lcidFound; } // Finally, attempt to load the library // Beware! A dll loaded with LOAD_LIBRARY_AS_DATAFILE won't // let you use LoadIcon and things like that (only general calls like // FindResource and LoadResource). if (phinstOut != NULL) { *phinstOut = LoadLibraryEx(szPathTemp, NULL, dwExFlags); hr = (*phinstOut) ? S_OK : E_FAIL; } if ( szFullPathOut ) { _tcsncpy_s(szFullPathOut,sizeInCharacters, szPathTemp, _MAX_PATH-1); } } return hr; }
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); } } }
void CDirectoryWatcher::WorkerThread() { DWORD numBytes; CDirWatchInfo * pdi = NULL; LPOVERLAPPED lpOverlapped; WCHAR buf[READ_DIR_CHANGE_BUFFER_SIZE] = {0}; WCHAR * pFound = NULL; while (m_bRunning) { CleanupWatchInfo(); if (watchedPaths.GetCount()) { // Any incoming notifications? pdi = NULL; numBytes = 0; InterlockedExchange(&m_bCleaned, FALSE); if ((!m_hCompPort) || !GetQueuedCompletionStatus(m_hCompPort, &numBytes, (PULONG_PTR) &pdi, &lpOverlapped, 600000 /*10 minutes*/)) { // No. Still trying? if (!m_bRunning) return; ATLTRACE(_T(": restarting watcher\n")); m_hCompPort.CloseHandle(); // We must sync the whole section because other threads may // receive "AddPath" calls that will delete the completion // port *while* we are adding references to it . AutoLocker lock(m_critSec); // Clear the list of watched objects and recreate that list. // This will also delete the old completion port ClearInfoMap(); CleanupWatchInfo(); for (int i=0; i<watchedPaths.GetCount(); ++i) { CTGitPath watchedPath = watchedPaths[i]; CAutoFile hDir = CreateFile(watchedPath.GetWinPath(), FILE_LIST_DIRECTORY, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, //security attributes OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | //required privileges: SE_BACKUP_NAME and SE_RESTORE_NAME. FILE_FLAG_OVERLAPPED, NULL); if (!hDir) { // this could happen if a watched folder has been removed/renamed ATLTRACE(_T("CDirectoryWatcher: CreateFile failed. Can't watch directory %s\n"), watchedPaths[i].GetWinPath()); watchedPaths.RemovePath(watchedPath); break; } DEV_BROADCAST_HANDLE NotificationFilter; SecureZeroMemory(&NotificationFilter, sizeof(NotificationFilter)); NotificationFilter.dbch_size = sizeof(DEV_BROADCAST_HANDLE); NotificationFilter.dbch_devicetype = DBT_DEVTYP_HANDLE; NotificationFilter.dbch_handle = hDir; // RegisterDeviceNotification sends a message to the UI thread: // make sure we *can* send it and that the UI thread isn't waiting on a lock int numPaths = watchedPaths.GetCount(); size_t numWatch = watchInfoMap.size(); lock.Unlock(); NotificationFilter.dbch_hdevnotify = RegisterDeviceNotification(hWnd, &NotificationFilter, DEVICE_NOTIFY_WINDOW_HANDLE); lock.Lock(); // since we released the lock to prevent a deadlock with the UI thread, // it could happen that new paths were added to watch, or another thread // could have cleared our info map. // if that happened, we have to restart watching all paths again. if ((numPaths != watchedPaths.GetCount()) || (numWatch != watchInfoMap.size())) { ClearInfoMap(); CleanupWatchInfo(); Sleep(200); break; } CDirWatchInfo * pDirInfo = new CDirWatchInfo(hDir, watchedPath); hDir.Detach(); // the new CDirWatchInfo object owns the handle now pDirInfo->m_hDevNotify = NotificationFilter.dbch_hdevnotify; HANDLE port = CreateIoCompletionPort(pDirInfo->m_hDir, m_hCompPort, (ULONG_PTR)pDirInfo, 0); if (port == NULL) { ATLTRACE(_T("CDirectoryWatcher: CreateIoCompletionPort failed. Can't watch directory %s\n"), watchedPath.GetWinPath()); // we must close the directory handle to allow ClearInfoMap() // to close the completion port properly pDirInfo->CloseDirectoryHandle(); ClearInfoMap(); CleanupWatchInfo(); delete pDirInfo; pDirInfo = NULL; watchedPaths.RemovePath(watchedPath); break; } m_hCompPort = port; if (!ReadDirectoryChangesW(pDirInfo->m_hDir, pDirInfo->m_Buffer, READ_DIR_CHANGE_BUFFER_SIZE, TRUE, FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME | FILE_NOTIFY_CHANGE_LAST_WRITE, &numBytes,// not used &pDirInfo->m_Overlapped, NULL)) //no completion routine! { ATLTRACE(_T("CDirectoryWatcher: ReadDirectoryChangesW failed. Can't watch directory %s\n"), watchedPath.GetWinPath()); // we must close the directory handle to allow ClearInfoMap() // to close the completion port properly pDirInfo->CloseDirectoryHandle(); ClearInfoMap(); CleanupWatchInfo(); delete pDirInfo; pDirInfo = NULL; watchedPaths.RemovePath(watchedPath); break; } ATLTRACE(_T("watching path %s\n"), pDirInfo->m_DirName.GetWinPath()); watchInfoMap[pDirInfo->m_hDir] = pDirInfo; } } else { if (!m_bRunning) return; if (watchInfoMap.empty()) continue; // NOTE: the longer this code takes to execute until ReadDirectoryChangesW // is called again, the higher the chance that we miss some // changes in the file system! if (pdi) { BOOL bRet = false; std::list<CTGitPath> notifyPaths; { AutoLocker lock(m_critSec); // in case the CDirectoryWatcher objects have been cleaned, // the m_bCleaned variable will be set to true here. If the // objects haven't been cleared, we can access them here. if (InterlockedExchange(&m_bCleaned, FALSE)) continue; if ( (!pdi->m_hDir) || watchInfoMap.empty() || (watchInfoMap.find(pdi->m_hDir) == watchInfoMap.end())) { continue; } PFILE_NOTIFY_INFORMATION pnotify = (PFILE_NOTIFY_INFORMATION)pdi->m_Buffer; DWORD nOffset = 0; do { pnotify = (PFILE_NOTIFY_INFORMATION)((LPBYTE)pnotify + nOffset); if ((ULONG_PTR)pnotify - (ULONG_PTR)pdi->m_Buffer > READ_DIR_CHANGE_BUFFER_SIZE) break; nOffset = pnotify->NextEntryOffset; if (pnotify->FileNameLength >= (READ_DIR_CHANGE_BUFFER_SIZE*sizeof(TCHAR))) continue; SecureZeroMemory(buf, READ_DIR_CHANGE_BUFFER_SIZE*sizeof(TCHAR)); _tcsncpy_s(buf, pdi->m_DirPath, _countof(buf) - 1); errno_t err = _tcsncat_s(buf + pdi->m_DirPath.GetLength(), READ_DIR_CHANGE_BUFFER_SIZE-pdi->m_DirPath.GetLength(), pnotify->FileName, min(READ_DIR_CHANGE_BUFFER_SIZE-pdi->m_DirPath.GetLength(), pnotify->FileNameLength/sizeof(TCHAR))); if (err == STRUNCATE) { continue; } buf[(pnotify->FileNameLength/sizeof(TCHAR))+pdi->m_DirPath.GetLength()] = 0; if (m_FolderCrawler) { if ((pFound = wcsstr(buf, L"\\tmp")) != NULL) { pFound += 4; if (((*pFound)=='\\')||((*pFound)=='\0')) { continue; } } if ((pFound = wcsstr(buf, L":\\RECYCLER\\")) != NULL) { if ((pFound-buf) < 5) { // a notification for the recycle bin - ignore it continue; } } if ((pFound = wcsstr(buf, L":\\$Recycle.Bin\\")) != NULL) { if ((pFound-buf) < 5) { // a notification for the recycle bin - ignore it continue; } } if (wcsstr(buf, L".tmp") != NULL) { // assume files with a .tmp extension are not versioned and interesting, // so ignore them. continue; } CTGitPath path; bool isIndex = false; if ((pFound = wcsstr(buf, L".git")) != NULL) { // omit repository data change except .git/index.lock- or .git/HEAD.lock-files if ((ULONG_PTR)pnotify - (ULONG_PTR)pdi->m_Buffer > READ_DIR_CHANGE_BUFFER_SIZE) break; path = g_AdminDirMap.GetWorkingCopy(CTGitPath(buf).GetContainingDirectory().GetWinPathString()); if ((wcsstr(pFound, L"index.lock") != NULL || wcsstr(pFound, L"HEAD.lock") != NULL) && pnotify->Action == FILE_ACTION_ADDED) { CGitStatusCache::Instance().BlockPath(path); continue; } else if (((wcsstr(pFound, L"index.lock") != NULL || wcsstr(pFound, L"HEAD.lock") != NULL) && pnotify->Action == FILE_ACTION_REMOVED) || (((wcsstr(pFound, L"index") != NULL && wcsstr(pFound, L"index.lock") == NULL) || (wcsstr(pFound, L"HEAD") != NULL && wcsstr(pFound, L"HEAD.lock") != NULL)) && pnotify->Action == FILE_ACTION_MODIFIED) || ((wcsstr(pFound, L"index.lock") == NULL || wcsstr(pFound, L"HEAD.lock") != NULL) && pnotify->Action == FILE_ACTION_RENAMED_NEW_NAME)) { isIndex = true; CGitStatusCache::Instance().BlockPath(path, 1); } else { continue; } } else path.SetFromUnknown(buf); if(!path.HasAdminDir() && !isIndex) continue; ATLTRACE(_T("change notification: %s\n"), buf); notifyPaths.push_back(path); } } while ((nOffset > 0)&&(nOffset < READ_DIR_CHANGE_BUFFER_SIZE)); // setup next notification cycle SecureZeroMemory (pdi->m_Buffer, sizeof(pdi->m_Buffer)); SecureZeroMemory (&pdi->m_Overlapped, sizeof(OVERLAPPED)); bRet = ReadDirectoryChangesW(pdi->m_hDir, pdi->m_Buffer, READ_DIR_CHANGE_BUFFER_SIZE, TRUE, FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME | FILE_NOTIFY_CHANGE_LAST_WRITE, &numBytes,// not used &pdi->m_Overlapped, NULL); //no completion routine! } if (!notifyPaths.empty()) { for (std::list<CTGitPath>::const_iterator nit = notifyPaths.begin(); nit != notifyPaths.end(); ++nit) { m_FolderCrawler->AddPathForUpdate(*nit); } } // any clean-up to do? CleanupWatchInfo(); if (!bRet) { // Since the call to ReadDirectoryChangesW failed, just // wait a while. We don't want to have this thread // running using 100% CPU if something goes completely // wrong. Sleep(200); } } } }// if (watchedPaths.GetCount()) else Sleep(200); }// while (m_bRunning) }
BOOL pthread_win32_process_attach_np () { TCHAR QuserExDLLPathBuf[1024]; BOOL result = TRUE; const UINT QuserExDLLPathBufSize = sizeof(QuserExDLLPathBuf) / sizeof(QuserExDLLPathBuf[0]); result = ptw32_processInitialize (); #if defined(_UWIN) pthread_count++; #endif #if defined(__GNUC__) ptw32_features = 0; #else /* * This is obsolete now. */ ptw32_features = PTW32_SYSTEM_INTERLOCKED_COMPARE_EXCHANGE; #endif /* * Load QUSEREX.DLL and try to get address of QueueUserAPCEx. * Because QUSEREX.DLL requires a driver to be installed we will * assume the DLL is in the system directory. * * This should take care of any security issues. */ #if defined(__GNUC__) || defined(PTW32_CONFIG_MSVC7) if(GetSystemDirectory(QuserExDLLPathBuf, QuserExDLLPathBufSize)) { (void) strncat(QuserExDLLPathBuf, "\\QUSEREX.DLL", QuserExDLLPathBufSize - strlen(QuserExDLLPathBuf) - 1); ptw32_h_quserex = LoadLibrary(QuserExDLLPathBuf); } #else /* strncat is secure - this is just to avoid a warning */ if(GetSystemDirectory(QuserExDLLPathBuf, QuserExDLLPathBufSize) && 0 == _tcsncat_s(QuserExDLLPathBuf, QuserExDLLPathBufSize, _T("\\QUSEREX.DLL"), 12)) { ptw32_h_quserex = LoadLibrary(QuserExDLLPathBuf); } #endif if (ptw32_h_quserex != NULL) { ptw32_register_cancellation = (DWORD (*)(PAPCFUNC, HANDLE, DWORD)) #if defined(NEED_UNICODE_CONSTS) GetProcAddress (ptw32_h_quserex, (const TCHAR *) TEXT ("QueueUserAPCEx")); #else GetProcAddress (ptw32_h_quserex, (LPCSTR) "QueueUserAPCEx"); #endif } if (NULL == ptw32_register_cancellation) { ptw32_register_cancellation = ptw32_Registercancellation; if (ptw32_h_quserex != NULL) { (void) FreeLibrary (ptw32_h_quserex); } ptw32_h_quserex = 0; } else { /* Initialise QueueUserAPCEx */ BOOL (*queue_user_apc_ex_init) (VOID); queue_user_apc_ex_init = (BOOL (*)(VOID)) #if defined(NEED_UNICODE_CONSTS) GetProcAddress (ptw32_h_quserex, (const TCHAR *) TEXT ("QueueUserAPCEx_Init")); #else GetProcAddress (ptw32_h_quserex, (LPCSTR) "QueueUserAPCEx_Init"); #endif if (queue_user_apc_ex_init == NULL || !queue_user_apc_ex_init ()) { ptw32_register_cancellation = ptw32_Registercancellation; (void) FreeLibrary (ptw32_h_quserex); ptw32_h_quserex = 0; } } if (ptw32_h_quserex) { ptw32_features |= PTW32_ALERTABLE_ASYNC_CANCEL; } return result; }
void CDirectoryWatcher::WorkerThread() { DWORD numBytes; CDirWatchInfo * pdi = NULL; LPOVERLAPPED lpOverlapped; WCHAR buf[READ_DIR_CHANGE_BUFFER_SIZE] = {0}; WCHAR * pFound = NULL; CTGitPath path; while (m_bRunning) { if (watchedPaths.GetCount()) { if (!GetQueuedCompletionStatus(m_hCompPort, &numBytes, (PULONG_PTR) &pdi, &lpOverlapped, INFINITE)) { // Error retrieving changes // Clear the list of watched objects and recreate that list if (!m_bRunning) return; { AutoLocker lock(m_critSec); ClearInfoMap(); } DWORD lasterr = GetLastError(); if ((m_hCompPort != INVALID_HANDLE_VALUE)&&(lasterr!=ERROR_SUCCESS)&&(lasterr!=ERROR_INVALID_HANDLE)) { CloseHandle(m_hCompPort); m_hCompPort = INVALID_HANDLE_VALUE; } // Since we pass m_hCompPort to CreateIoCompletionPort, we // have to set this to NULL to have that API create a new // handle. m_hCompPort = NULL; for (int i=0; i<watchedPaths.GetCount(); ++i) { CTGitPath watchedPath = watchedPaths[i]; HANDLE hDir = CreateFile(watchedPath.GetWinPath(), FILE_LIST_DIRECTORY, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, //security attributes OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | //required privileges: SE_BACKUP_NAME and SE_RESTORE_NAME. FILE_FLAG_OVERLAPPED, NULL); if (hDir == INVALID_HANDLE_VALUE) { // this could happen if a watched folder has been removed/renamed ATLTRACE(_T("CDirectoryWatcher: CreateFile failed. Can't watch directory %s\n"), watchedPaths[i].GetWinPath()); CloseHandle(m_hCompPort); m_hCompPort = INVALID_HANDLE_VALUE; AutoLocker lock(m_critSec); watchedPaths.RemovePath(watchedPath); i--; if (i<0) i=0; break; } DEV_BROADCAST_HANDLE NotificationFilter; SecureZeroMemory(&NotificationFilter, sizeof(NotificationFilter)); NotificationFilter.dbch_size = sizeof(DEV_BROADCAST_HANDLE); NotificationFilter.dbch_devicetype = DBT_DEVTYP_HANDLE; NotificationFilter.dbch_handle = hDir; NotificationFilter.dbch_hdevnotify = RegisterDeviceNotification(hWnd, &NotificationFilter, DEVICE_NOTIFY_WINDOW_HANDLE); CDirWatchInfo * pDirInfo = new CDirWatchInfo(hDir, watchedPath); pDirInfo->m_hDevNotify = NotificationFilter.dbch_hdevnotify; m_hCompPort = CreateIoCompletionPort(hDir, m_hCompPort, (ULONG_PTR)pDirInfo, 0); if (m_hCompPort == NULL) { ATLTRACE(_T("CDirectoryWatcher: CreateIoCompletionPort failed. Can't watch directory %s\n"), watchedPath.GetWinPath()); AutoLocker lock(m_critSec); ClearInfoMap(); delete pDirInfo; pDirInfo = NULL; watchedPaths.RemovePath(watchedPath); i--; if (i<0) i=0; break; } if (!ReadDirectoryChangesW(pDirInfo->m_hDir, pDirInfo->m_Buffer, READ_DIR_CHANGE_BUFFER_SIZE, TRUE, FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME | FILE_NOTIFY_CHANGE_LAST_WRITE, &numBytes,// not used &pDirInfo->m_Overlapped, NULL)) //no completion routine! { ATLTRACE(_T("CDirectoryWatcher: ReadDirectoryChangesW failed. Can't watch directory %s\n"), watchedPath.GetWinPath()); AutoLocker lock(m_critSec); ClearInfoMap(); delete pDirInfo; pDirInfo = NULL; watchedPaths.RemovePath(watchedPath); i--; if (i<0) i=0; break; } AutoLocker lock(m_critSec); watchInfoMap[pDirInfo->m_hDir] = pDirInfo; ATLTRACE(_T("watching path %s\n"), pDirInfo->m_DirName.GetWinPath()); } } else { if (!m_bRunning) return; // NOTE: the longer this code takes to execute until ReadDirectoryChangesW // is called again, the higher the chance that we miss some // changes in the file system! if (pdi) { if (numBytes == 0) { goto continuewatching; } PFILE_NOTIFY_INFORMATION pnotify = (PFILE_NOTIFY_INFORMATION)pdi->m_Buffer; if ((ULONG_PTR)pnotify - (ULONG_PTR)pdi->m_Buffer > READ_DIR_CHANGE_BUFFER_SIZE) goto continuewatching; DWORD nOffset = pnotify->NextEntryOffset; do { nOffset = pnotify->NextEntryOffset; if (pnotify->FileNameLength >= (READ_DIR_CHANGE_BUFFER_SIZE*sizeof(TCHAR))) continue; SecureZeroMemory(buf, READ_DIR_CHANGE_BUFFER_SIZE*sizeof(TCHAR)); _tcsncpy_s(buf, READ_DIR_CHANGE_BUFFER_SIZE, pdi->m_DirPath, READ_DIR_CHANGE_BUFFER_SIZE); errno_t err = _tcsncat_s(buf+pdi->m_DirPath.GetLength(), READ_DIR_CHANGE_BUFFER_SIZE-pdi->m_DirPath.GetLength(), pnotify->FileName, _TRUNCATE); if (err == STRUNCATE) { pnotify = (PFILE_NOTIFY_INFORMATION)((LPBYTE)pnotify + nOffset); continue; } buf[(pnotify->FileNameLength/sizeof(TCHAR))+pdi->m_DirPath.GetLength()] = 0; pnotify = (PFILE_NOTIFY_INFORMATION)((LPBYTE)pnotify + nOffset); if (m_FolderCrawler) { if ((pFound = wcsstr(buf, L"\\tmp"))!=NULL) { pFound += 4; if (((*pFound)=='\\')||((*pFound)=='\0')) { if ((ULONG_PTR)pnotify - (ULONG_PTR)pdi->m_Buffer > READ_DIR_CHANGE_BUFFER_SIZE) break; continue; } } if ((pFound = wcsstr(buf, L":\\RECYCLER\\"))!=NULL) { if ((pFound-buf) < 5) { // a notification for the recycle bin - ignore it if ((ULONG_PTR)pnotify - (ULONG_PTR)pdi->m_Buffer > READ_DIR_CHANGE_BUFFER_SIZE) break; continue; } } if ((pFound = wcsstr(buf, L":\\$Recycle.Bin\\"))!=NULL) { if ((pFound-buf) < 5) { // a notification for the recycle bin - ignore it if ((ULONG_PTR)pnotify - (ULONG_PTR)pdi->m_Buffer > READ_DIR_CHANGE_BUFFER_SIZE) break; continue; } } if ((pFound = wcsstr(buf, L".tmp"))!=NULL) { // assume files with a .tmp extension are not versioned and interesting, // so ignore them. if ((ULONG_PTR)pnotify - (ULONG_PTR)pdi->m_Buffer > READ_DIR_CHANGE_BUFFER_SIZE) break; continue; } bool isIndex = false; if ((pFound = wcsstr(buf, L".git"))!=NULL) { // omit repository data change except .git/index.lock- or .git/HEAD.lock-files if ((ULONG_PTR)pnotify - (ULONG_PTR)pdi->m_Buffer > READ_DIR_CHANGE_BUFFER_SIZE) break; if ((wcsstr(pFound, L"index.lock") != NULL && wcsstr(pFound, L"HEAD.lock") != NULL) && pnotify->Action == FILE_ACTION_ADDED) { m_FolderCrawler->BlockPath(CTGitPath(buf).GetContainingDirectory().GetContainingDirectory()); // optimize here, and use general BlockPath with priorities continue; } else if ((wcsstr(pFound, L"index.lock") != NULL && wcsstr(pFound, L"HEAD.lock") != NULL) && pnotify->Action == FILE_ACTION_REMOVED) { isIndex = true; m_FolderCrawler->BlockPath(CTGitPath(buf).GetContainingDirectory().GetContainingDirectory(), 1); } else { continue; } } path.SetFromWin(buf); if(!path.HasAdminDir() && !isIndex) continue; ATLTRACE(_T("change notification: %s\n"), buf); m_FolderCrawler->AddPathForUpdate(CTGitPath(buf)); } if ((ULONG_PTR)pnotify - (ULONG_PTR)pdi->m_Buffer > READ_DIR_CHANGE_BUFFER_SIZE) break; } while (nOffset); continuewatching: SecureZeroMemory(pdi->m_Buffer, sizeof(pdi->m_Buffer)); SecureZeroMemory(&pdi->m_Overlapped, sizeof(OVERLAPPED)); if (!ReadDirectoryChangesW(pdi->m_hDir, pdi->m_Buffer, READ_DIR_CHANGE_BUFFER_SIZE, TRUE, FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME | FILE_NOTIFY_CHANGE_LAST_WRITE, &numBytes,// not used &pdi->m_Overlapped, NULL)) //no completion routine! { // Since the call to ReadDirectoryChangesW failed, just // wait a while. We don't want to have this thread // running using 100% CPU if something goes completely // wrong. Sleep(200); } } } } // if (watchedPaths.GetCount()) else Sleep(200); } // while (m_bRunning) }
/***************************************************************************************** * FUNCTION: ScenarioThread() (a thread process) * * PARAMETERS: * LPVOID lpParameter: A pointer to the GLOBALDATA struct. * * RETURN VALUE: * DWORD value 0. Holds no meaning at this time. * * REVISION HISTORY: * Date Name Change * -------- ---- ------ * * DESCRIPTION: * This thread runs the 3mb scenario, runs the process that extracts data from a * file, and provides feedback to the parent process's GUI. Scenario execution and * data extraction are done within this thread because 3mb has a GUI format and by * running these processes in threads the GUI doesn't lock up and feedback can be * presented to the user. *****************************************************************************************/ DWORD WINAPI ScenarioThread(LPVOID lpParameter) { GLOBALDATA *gdata = (GLOBALDATA *)lpParameter; //SCESTATE sceState; RESLT mbsRes; HWND hwnd; int index; static TCHAR szBuff[SIZE_128]; static TCHAR szBuff2[SIZE_128]; static TCHAR szBuffCaption[SIZE_128]; //size_t bufferLen; // length (not size) of the buffer in terms of the number of characters it holds. USERPARAMS usrPrms; // scenario user params DWORD startTick = GetTickCount(); DWORD totAniCnt; DWORD duration; BOOL windowPreviouslyDisabled; SCEACTIVITY sceAct; //int remSecs = 0; //HHMMSS hhmmss; //INT_PTR dlgRes = IDCANCEL; //BOOL ofnRes = FALSE; //DWORD updateCount; //BOOL abort; // Verify only a single instance of this thread is running. Catch it in debug mode // with an assertion and handle it in release mode with a return. _ASSERT(gdata->sceRunThreadInf.running == FALSE); _ASSERT(gdata->sceRunThreadInf.exit == FALSE); if(gdata->sceRunThreadInf.running == TRUE) return 0; // Indicate This thread is running. gdata->sceRunThreadInf.running = TRUE; gdata->sce.SetOutputDirectory(gdata->szOutputFolder); //----------------------------------------------------------------------------------// // Launch the scenario process thread. //------------------------------------// totAniCnt = gdata->sce.GetAnimatCount(); duration = gdata->sce.GetDurationSeconds(); if(OK == (mbsRes = gdata->sce.RunScenario())) { UpdateRunScenario(gdata, totAniCnt, duration, INITIALIZE, startTick); PostMessage(gdata->hwin, WM_UPDATE_GUI, NULL, NULL); // Enable run button so user may abort run EnableWindow(GetDlgItem(gdata->hwin, ID_RUN_SIMULATION), TRUE); // Provide some initial feedback to the user hwnd = GetDlgItem(gdata->hwin, IDC_LIST_MESSAGES); index = SendMessage(hwnd, LB_ADDSTRING, 0, (LPARAM)"Initializing Simulation..."); SendMessage(hwnd, LB_SETCARETINDEX , index, 0); PostMessage(gdata->hwin, WM_UPDATE_GUI, NULL, NULL); // Continuously poll the extraction process and update the GUI until either the // user aborts or the scenario process finishes. sceAct = gdata->sce.GetState().activity; while(gdata->sceRunThreadInf.exit == FALSE && sceAct != __RUN_FINISHED) { UpdateRunScenario(gdata, totAniCnt, duration); #if 0 windowPreviouslyDisabled = EnableWindow(gdata->hwin, TRUE); if(windowPreviouslyDisabled != FALSE) windowPreviouslyDisabled = FALSE; #endif Sleep(25); sceAct = gdata->sce.GetState().activity; } // If the user aborted the simulation then signal the simulation process to abort // and wait until it indicates it is finished running. if(gdata->sceRunThreadInf.exit == TRUE) { gdata->sce.AbortRun(); while(gdata->sce.GetState().activity != __RUN_FINISHED) Sleep(30); } UpdateRunScenario(gdata, totAniCnt, duration); } // Handle the various ways the scenario execution may have ceased. if(gdata->sceRunThreadInf.exit == TRUE) { // The user aborted. Post a message. strncpy_s(szBuff, sizeof(szBuff), "Run aborted", sizeof(szBuff)); PostMessage(gdata->hwin, WM_ADD_LIST_BOX_MESSAGE, 0, (LPARAM)szBuff); } else if(mbsRes != OK) { // There was an error with the extraction process memset(szBuff, 0, sizeof(szBuff)); staticLib.MbsResultToString(mbsRes, szBuff, sizeof(szBuff), szBuffCaption, sizeof(szBuff)); MessageBox(gdata->hwin, szBuff, szBuffCaption, MB_ICONHAND); } else if(gdata->sce.GetState().errorStatus != OK) { memset(szBuff, 0, sizeof(szBuff)); staticLib.MbsResultToString(gdata->sce.GetState().errorStatus, szBuff, sizeof(szBuff), szBuffCaption, sizeof(szBuffCaption)); MessageBox(gdata->hwin, szBuff, szBuffCaption, MB_ICONHAND); } else // scenario finished execution { PostMessage(gdata->hwin, WM_UPDATE_PROGRESS_BAR, 100, 0); strncpy_s(szBuff, sizeof(szBuff), "Done", sizeof(szBuff)); PostMessage(gdata->hwin, WM_ADD_LIST_BOX_MESSAGE , 0, (LPARAM)szBuff); UpdateRunScenario(gdata, totAniCnt, duration, FINALIZE); } //////////////////////////////////////////////////////////////////////////////////////////// // Post simulation variable assignment gdata->sceRunThreadInf.running = FALSE; gdata->sceRunThreadInf.exit = FALSE; PostMessage(gdata->hwin, WM_UPDATE_GUI, NULL, NULL); if(gdata->textOutputConfig.enabled == TRUE && gdata->sce.GetConfiguration().output.enabled == TRUE) { //88888888888888888888888888888888888888888888888888888888888888888888888888888888888// _ASSERT(gdata->extractThreadInf.running == FALSE); if(gdata->extractThreadInf.running == TRUE) { // Launch the proces that waits for the scenario execution and data // extractions processes to cease. gdata->sceAbortThreadInf.hdl = CreateThread(NULL, 0, &AbortProcessThreadProc, gdata, 0, &gdata->sceAbortThreadInf.id); } while(gdata->extractThreadInf.running == TRUE) Sleep(100); //------------------------------------------------------------------------------// // Initialize the OFN (Open File Name) struct for the data extractor //------------------------------------------------------------------// usrPrms = gdata->sce.GetConfiguration(); // Reference the OFN string pointers to point to the appropriate TCHAR buffers. // Commented out 11/2/09 //gdata->extractThreadInf.fileInf.ofn.lpstrFile = gdata->extractThreadInf.fileInf.szFileName; //gdata->extractThreadInf.fileInf.ofn.lpstrFileTitle = gdata->extractThreadInf.fileInf.szTitleName; // Set up the file name (file name plus path). _stprintf_s(gdata->extractThreadInf.fileInf.szFileName, // Destination buffer TCHARBFLEN(gdata->extractThreadInf.fileInf.szFileName), // Destination buffer size (length) "%s\\%s", // Format usrPrms.szOutputDir, usrPrms.szScenarioTitle); // Format paramaters // Commented out 11/2/09 // RemoveExtension(gdata->extractThreadInf.fileInf.szFileName); _tcsncat_s(gdata->extractThreadInf.fileInf.szFileName, TCHARBFLEN(gdata->extractThreadInf.fileInf.szFileName), ".3mb", _tcslen(".3mb")+1); // Set up the file title (no path) _tcsncpy_s(gdata->extractThreadInf.fileInf.szTitleName, TCHARBFLEN(gdata->extractThreadInf.fileInf.szTitleName), usrPrms.szScenarioTitle, _tcslen(usrPrms.szScenarioTitle)); // RemoveExtension(gdata->extractThreadInf.fileInf.szTitleName); _tcsncat_s(gdata->extractThreadInf.fileInf.szTitleName, TCHARBFLEN(gdata->extractThreadInf.fileInf.szTitleName), ".3mb", _tcslen(".3mb")+1); //------------------------------------------------------------------------------// PostMessage(gdata->hwin, WM_3MBS_EXTRACT_BIN_TO_TEXT, NULL, NULL); //88888888888888888888888888888888888888888888888888888888888888888888888888888888888// } return 0; }
int CMPIPTV_RTSP::ParseUrl(const TCHAR *url, const CParameterCollection *parameters) { int result = STATUS_OK; this->logger.Log(LOGGER_INFO, METHOD_START_FORMAT, PROTOCOL_IMPLEMENTATION_NAME, METHOD_PARSE_URL_NAME); this->ClearSession(); this->loadParameters->Append((CParameterCollection *)parameters); this->loadParameters->LogCollection(&this->logger, LOGGER_VERBOSE, PROTOCOL_IMPLEMENTATION_NAME, METHOD_PARSE_URL_NAME); ALLOC_MEM_DEFINE_SET(urlComponents, URL_COMPONENTS, 1, 0); if (urlComponents == NULL) { this->logger.Log(LOGGER_ERROR, METHOD_MESSAGE_FORMAT, PROTOCOL_IMPLEMENTATION_NAME, METHOD_PARSE_URL_NAME, _T("cannot allocate memory for 'url components'")); result = STATUS_ERROR; } if (result == STATUS_OK) { ZeroURL(urlComponents); urlComponents->dwStructSize = sizeof(URL_COMPONENTS); this->logger.Log(LOGGER_INFO, _T("%s: %s: url: %s"), PROTOCOL_IMPLEMENTATION_NAME, METHOD_PARSE_URL_NAME, url); if (!InternetCrackUrl(url, 0, 0, urlComponents)) { this->logger.Log(LOGGER_ERROR, _T("%s: %s: InternetCrackUrl() error: %u"), PROTOCOL_IMPLEMENTATION_NAME, METHOD_PARSE_URL_NAME, GetLastError()); result = STATUS_ERROR; } } if (result == STATUS_OK) { int length = urlComponents->dwSchemeLength + 1; ALLOC_MEM_DEFINE_SET(protocol, TCHAR, length, 0); if (protocol == NULL) { this->logger.Log(LOGGER_ERROR, METHOD_MESSAGE_FORMAT, PROTOCOL_IMPLEMENTATION_NAME, METHOD_PARSE_URL_NAME, _T("cannot allocate memory for 'protocol'")); result = STATUS_ERROR; } if (result == STATUS_OK) { _tcsncat_s(protocol, length, urlComponents->lpszScheme, urlComponents->dwSchemeLength); if (_tcsncicmp(urlComponents->lpszScheme, _T("RTSP"), urlComponents->dwSchemeLength) != 0) { // not supported protocol this->logger.Log(LOGGER_INFO, _T("%s: %s: unsupported protocol '%s'"), PROTOCOL_IMPLEMENTATION_NAME, METHOD_PARSE_URL_NAME, protocol); result = STATUS_ERROR; } } FREE_MEM(protocol); if (result == STATUS_OK) { length = _tcslen(url) + 1; this->rtspUrl = ALLOC_MEM_SET(this->rtspUrl, TCHAR, length, 0); if (this->rtspUrl == NULL) { this->logger.Log(LOG_ERROR, METHOD_MESSAGE_FORMAT, PROTOCOL_IMPLEMENTATION_NAME, METHOD_PARSE_URL_NAME, _T("cannot allocate memory for RTSP url")); result = STATUS_ERROR; } } if (result == STATUS_OK) { _tcscpy_s(this->rtspUrl, length, url); this->logger.Log(LOGGER_INFO, _T("%s: %s: RTSP url: %s"), PROTOCOL_IMPLEMENTATION_NAME, METHOD_PARSE_URL_NAME, this->rtspUrl); } } FREE_MEM(urlComponents); this->logger.Log(LOGGER_INFO, (result == STATUS_OK) ? METHOD_END_FORMAT : METHOD_END_FAIL_FORMAT, PROTOCOL_IMPLEMENTATION_NAME, METHOD_PARSE_URL_NAME); return result; }
char* CSingleInstance::CreateUniqueName(const char* pszGUID, char* pszBuffer, int nMode /* = SI_DESKTOP_UNIQUE */) { if(pszBuffer == NULL) { SetLastError(ERROR_INVALID_PARAMETER); return NULL; } // First copy GUID to destination buffer if(pszGUID) _tcscpy_s(pszBuffer, MAX_PATH, pszGUID); else *pszBuffer = 0; // Name should be desktop unique, so add current desktop name if(nMode & SI_DESKTOP_UNIQUE) { _tcscat_s(pszBuffer, MAX_PATH, _T("-")); HDESK hDesk = GetThreadDesktop(GetCurrentThreadId()); ULONG cchDesk = MAX_PATH - (_tcslen(pszBuffer) + 1); if(!GetUserObjectInformation(hDesk, UOI_NAME, pszBuffer + _tcslen(pszBuffer), cchDesk, &cchDesk)) // Call will fail on Win9x _tcsncat_s(pszBuffer, MAX_PATH, _T("Win9x"), cchDesk); } // Name should be session unique, so add current session id if(nMode & SI_SESSION_UNIQUE) { HANDLE hToken = NULL; // Try to open the token (fails on Win9x) and check necessary buffer size if(OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken) && (MAX_PATH - _tcslen(pszBuffer) > 9 )) { DWORD cbBytes = 0; if(!GetTokenInformation(hToken, TokenStatistics, NULL, cbBytes, &cbBytes) && GetLastError() == ERROR_INSUFFICIENT_BUFFER ) { PTOKEN_STATISTICS pTS = (PTOKEN_STATISTICS) _alloca( cbBytes ); if(GetTokenInformation(hToken, TokenStatistics, (LPVOID)pTS, cbBytes, &cbBytes)) { wsprintf(pszBuffer + _tcslen(pszBuffer), _T("-%08x%08x"), pTS->AuthenticationId.HighPart, pTS->AuthenticationId.LowPart); } } } } // Name should be unique to the current user if(nMode & SI_TRUSTEE_UNIQUE) { TCHAR szUser[64] = {0}; TCHAR szDomain[64] = {0}; DWORD cchUser = 64; DWORD cchDomain = 64; if(GetUserName(szUser, &cchUser)) { // Since NetApi() calls are quite time consuming // we retrieve the domain name from an environment variable cchDomain = GetEnvironmentVariable(_T("USERDOMAIN"), szDomain, cchDomain); UINT cchUsed = _tcslen(pszBuffer); if(MAX_PATH - cchUsed > cchUser + cchDomain + 3) { wsprintf(pszBuffer + cchUsed, _T("-%s-%s"), szDomain, szUser); } } } return pszBuffer; }
void CPathWatcher::WorkerThread() { DWORD numBytes; CDirWatchInfo * pdi = NULL; LPOVERLAPPED lpOverlapped; WCHAR buf[MAX_PATH*4] = {0}; while (m_bRunning) { if (watchedPaths.GetCount()) { if (!GetQueuedCompletionStatus(m_hCompPort, &numBytes, (PULONG_PTR) &pdi, &lpOverlapped, INFINITE)) { // Error retrieving changes // Clear the list of watched objects and recreate that list if (!m_bRunning) return; { AutoLocker lock(m_critSec); ClearInfoMap(); } DWORD lasterr = GetLastError(); if ((m_hCompPort != INVALID_HANDLE_VALUE)&&(lasterr!=ERROR_SUCCESS)&&(lasterr!=ERROR_INVALID_HANDLE)) { CloseHandle(m_hCompPort); m_hCompPort = INVALID_HANDLE_VALUE; } // Since we pass m_hCompPort to CreateIoCompletionPort, we // have to set this to NULL to have that API create a new // handle. m_hCompPort = NULL; for (int i=0; i<watchedPaths.GetCount(); ++i) { HANDLE hDir = CreateFile(watchedPaths[i].GetWinPath(), FILE_LIST_DIRECTORY, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, //security attributes OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | //required privileges: SE_BACKUP_NAME and SE_RESTORE_NAME. FILE_FLAG_OVERLAPPED, NULL); if (hDir == INVALID_HANDLE_VALUE) { // this could happen if a watched folder has been removed/renamed CloseHandle(m_hCompPort); m_hCompPort = INVALID_HANDLE_VALUE; AutoLocker lock(m_critSec); watchedPaths.RemovePath(watchedPaths[i]); i--; if (i<0) i=0; break; } CDirWatchInfo * pDirInfo = new CDirWatchInfo(hDir, watchedPaths[i]); m_hCompPort = CreateIoCompletionPort(hDir, m_hCompPort, (ULONG_PTR)pDirInfo, 0); if (m_hCompPort == NULL) { AutoLocker lock(m_critSec); ClearInfoMap(); delete pDirInfo; pDirInfo = NULL; watchedPaths.RemovePath(watchedPaths[i]); i--; if (i<0) i=0; break; } if (!ReadDirectoryChangesW(pDirInfo->m_hDir, pDirInfo->m_Buffer, READ_DIR_CHANGE_BUFFER_SIZE, TRUE, FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME | FILE_NOTIFY_CHANGE_LAST_WRITE, &numBytes,// not used &pDirInfo->m_Overlapped, NULL)) //no completion routine! { AutoLocker lock(m_critSec); ClearInfoMap(); delete pDirInfo; pDirInfo = NULL; watchedPaths.RemovePath(watchedPaths[i]); i--; if (i<0) i=0; break; } AutoLocker lock(m_critSec); watchInfoMap[pDirInfo->m_hDir] = pDirInfo; ATLTRACE(_T("watching path %s\n"), pDirInfo->m_DirName.GetWinPath()); } } else { if (!m_bRunning) return; // NOTE: the longer this code takes to execute until ReadDirectoryChangesW // is called again, the higher the chance that we miss some // changes in the file system! if (pdi) { if (numBytes == 0) { goto continuewatching; } PFILE_NOTIFY_INFORMATION pnotify = (PFILE_NOTIFY_INFORMATION)pdi->m_Buffer; if ((ULONG_PTR)pnotify - (ULONG_PTR)pdi->m_Buffer > READ_DIR_CHANGE_BUFFER_SIZE) goto continuewatching; DWORD nOffset = pnotify->NextEntryOffset; do { nOffset = pnotify->NextEntryOffset; SecureZeroMemory(buf, MAX_PATH*4*sizeof(TCHAR)); _tcsncpy_s(buf, MAX_PATH*4, pdi->m_DirPath, MAX_PATH*4); errno_t err = _tcsncat_s(buf+pdi->m_DirPath.GetLength(), (MAX_PATH*4)-pdi->m_DirPath.GetLength(), pnotify->FileName, _TRUNCATE); if (err == STRUNCATE) { pnotify = (PFILE_NOTIFY_INFORMATION)((LPBYTE)pnotify + nOffset); continue; } buf[min(MAX_PATH*4-1, pdi->m_DirPath.GetLength()+(pnotify->FileNameLength/sizeof(WCHAR)))] = 0; pnotify = (PFILE_NOTIFY_INFORMATION)((LPBYTE)pnotify + nOffset); ATLTRACE(_T("change notification: %s\n"), buf); m_changedPaths.AddPath(CTGitPath(buf)); if ((ULONG_PTR)pnotify - (ULONG_PTR)pdi->m_Buffer > READ_DIR_CHANGE_BUFFER_SIZE) break; } while (nOffset); continuewatching: SecureZeroMemory(pdi->m_Buffer, sizeof(pdi->m_Buffer)); SecureZeroMemory(&pdi->m_Overlapped, sizeof(OVERLAPPED)); if (!ReadDirectoryChangesW(pdi->m_hDir, pdi->m_Buffer, READ_DIR_CHANGE_BUFFER_SIZE, TRUE, FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME | FILE_NOTIFY_CHANGE_LAST_WRITE, &numBytes,// not used &pdi->m_Overlapped, NULL)) //no completion routine! { // Since the call to ReadDirectoryChangesW failed, just // wait a while. We don't want to have this thread // running using 100% CPU if something goes completely // wrong. Sleep(200); } } } }// if (watchedPaths.GetCount()) else Sleep(200); }// while (m_bRunning) }
int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE /*hPrevInstance*/, LPTSTR lpstrCmdLine, int nCmdShow) { HRESULT hRes = ::CoInitialize(NULL); // If you are running on NT 4.0 or higher you can use the following call instead to // make the EXE free threaded. This means that calls come in on a random RPC thread. // HRESULT hRes = ::CoInitializeEx(NULL, COINIT_MULTITHREADED); ATLASSERT(SUCCEEDED(hRes)); // this resolves ATL window thunking problem when Microsoft Layer for Unicode (MSLU) is used ::DefWindowProc(NULL, 0, 0, 0L); AtlInitCommonControls(ICC_BAR_CLASSES); // add flags to support other controls hRes = _Module.Init(NULL, hInstance); ATLASSERT(SUCCEEDED(hRes)); int nRet = 0;//Run(lpstrCmdLine, nCmdShow); CString ProgramFile; CString lpszArgument(lpstrCmdLine); TCHAR szFilePath[MAX_URI], szIniPath[MAX_URI]; GetModuleFileName(NULL, szFilePath, MAX_URI); (_tcsrchr(szFilePath, _T('\\')))[1] = 0; _tcsncpy_s(szIniPath, MAX_URI, szFilePath, MAX_URI); _tcsncat_s(szIniPath, MAX_URI, _T("mloader.ini"), MAX_URI); TCHAR *mainpath = _tcsstr(szFilePath, _T("\\codecs\\Real")); if(mainpath) mainpath[1] = 0; _tcsncat_s(szFilePath, MAX_URI, _T("mplayer.exe"), MAX_URI); ProgramFile = szFilePath; if(IsFileExist(szIniPath)) { TCHAR temp[MAX_URI]; GetPrivateProfileString(_T("Command"), _T("Program_Path"), _T(""), temp, MAX_URI, szIniPath); if(_tcslen(temp) > 3) ProgramFile = temp; } int index = lpszArgument.Find(_T("/command:Screensize(full)")); if(index >= 0) lpszArgument.Delete(index, _tcslen(_T("/command:Screensize(full)"))); index = lpszArgument.Find(_T("\"")); if(index >= 0) { int len = lpszArgument.Find(_T("\""), index+1); if(len > index) { CString url = lpszArgument.Mid(index+1, len-index-1); if(url.Find(_T("http://")) >= 0) { std::string surl; if(GetRealURL(url.GetBuffer(), 4096, surl)) url = surl.c_str(); if(url.Find(_T("rtsp://")) >= 0) lpszArgument = _T("\"") + url + _T("\""); } } } ShellExecute(0, _T("open"), ProgramFile, lpszArgument, NULL, SW_SHOW); _Module.Term(); ::CoUninitialize(); return nRet; }
const std::string ReadLoginHistory(std::string &strLog) { TCHAR szPath[_MAX_PATH] = {0}; _tcscpy_s(szPath, crash::GetCrashPath()); _tcsncat_s(szPath, _countof(szPath), _T("login_history.txt"), _TRUNCATE); std::string strRet; HANDLE hFile = ::CreateFile(szPath, GENERIC_WRITE|GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, NULL, NULL); if (hFile != INVALID_HANDLE_VALUE) { DWORD dwSize = ::GetFileSize(hFile, NULL); void *pBuf = new BYTE[dwSize + sizeof(char)]; DWORD dwReadBytes = 0; ::ReadFile(hFile, pBuf, dwSize, &dwReadBytes, NULL); // >1024 就认为是非法的 if(dwSize<=32 || dwSize>1024) { return strRet; } *((char*)pBuf + dwReadBytes) = 0; char *p = (char*)pBuf; int nLineCount = 0; strLog = (char*)pBuf; // \r\n 换成 & while (*p) { if (*p == '\r') { nLineCount++; if(nLineCount>3) { *p = 0; break; } if( (*(p+1)) && (*(p+2)) ) { strRet += '&'; } if(*(p+1) && *(p+1) == '\n') { *p++; } } else { strRet += *p; } p++; } ::CloseHandle(hFile); delete []pBuf; } return strRet; }