map<string, string> ParseShdFromString(const string &acc) { map<string, string> mapNameShd; P p(acc); while (true) { string markS("======"), markE("@@@@@@"); P pS(p); bool afterNextDelS = pS.OptAfterNextDelShallow(markS); P pE(pS); bool afterNextDelE = pE.OptAfterNextDelDeep(markE); if (! (afterNextDelS && afterNextDelE)) break; string shdNameSpan(pS.OptRawSpanTo(pE)); assert(shdNameSpan.size() >= markE.size() && equal(markE.begin(), markE.end(), shdNameSpan.rbegin())); string shdName(StrTrim(shdNameSpan.substr(0, shdNameSpan.size() - markE.size()))); P pContentS(pE); P pContentE(pContentS); bool afterNextDelContent = pContentE.OptAfterNextDelDeep(markS); if (afterNextDelContent) { pContentE.AdvanceN(- (int)markS.size()); mapNameShd[shdName] = StrTrim(pContentS.OptRawSpanTo(pContentE)); } else { mapNameShd[shdName] = StrTrim(pContentS.OptRawSpanToEnd()); } p = pContentE; } return mapNameShd; }
bool CVcardView::GetNameAndNumber(char* name, char* mobile_number, char* home_number, char* line) { char flag[] = "#;/" ; // 注释 if ((line[0] == flag[0]) || (line[0] == flag[1]) || (line[0] == flag[2])) return false; // 清零 name[0] = '\0' ; mobile_number[0] = '\0' ; home_number[0] = '\0' ; char* pch; char* delimiters = ",;\t\n\"\'"; pch = strtok(line, delimiters); if (pch != NULL) { sprintf(name, "%s", pch); pch = strtok(NULL, delimiters); if (pch != NULL) { sprintf(mobile_number, "%s", pch); pch = strtok(NULL, delimiters); if (pch != NULL) sprintf(home_number, "%s", pch); } } // 删除前后空格 StrTrim(name); StrTrim(mobile_number); StrTrim(home_number); return true; }
void StrSplit(const char *pszStr,vector<string> &vStr,const char* strDelim) { int iLen = strlen(pszStr) + 1; char * pszCopy = new char[iLen]; memset(pszCopy,0,iLen); strcpy_s(pszCopy,iLen,pszStr); char *toKen; char *Out = NULL; toKen = strtok_s(pszCopy,strDelim,&Out); string str = toKen; str = StrTrim(str.c_str()); if (!str.empty()) vStr.push_back(str); while(toKen!=NULL) { toKen = strtok_s(NULL,strDelim,&Out); if (toKen) { str = toKen; str = StrTrim(str.c_str()); if (!str.empty()) vStr.push_back(str); } } delete pszCopy; }
int Messages_Init_Parse_Line (char *line) { char * p; //char * p2; int ret; if (line[0] == '[') { line = strdup(line); // Work on a copy if ((p = strchr(line, ']')) != NULL) *p = EOSTR; Messages.Lang_Cur = Lang_New(line + 1); if (Messages.Lang_Default == NULL) Messages.Lang_Default = Messages.Lang_Cur; free(line); return (MEKA_ERR_OK); } if (Messages.Lang_Cur == NULL) return (MEKA_ERR_MISSING); if (stricmp(line, MSG_LANG_WIP_STR) == 0) { Messages.Lang_Cur->WIP = TRUE; return (MEKA_ERR_OK); } line = strdup(line); // Work on a copy if ((p = strchr(line, '=')) == NULL) { free(line); return (MEKA_ERR_SYNTAX); } *p = EOSTR; StrTrim (line); StrUpper(line); StrTrim (p + 1); if ((p = strchr (p + 1, '\"')) == NULL) { free(line); return (MEKA_ERR_SYNTAX); } // if ((p2 = strrchr (p + 1, '\"')) == NULL) // return (MEKA_ERR_SYNTAX); // *p2 = EOSTR; ret = Lang_Message_Add(Messages.Lang_Cur, line, p + 1); free(line); return (ret); }
APIRET InteractiveConsole(void) { BOOL flagTerminate = FALSE; PSZ pszLine; /* returned line from file */ int rc; /* operation return code */ char pszLineBuffer[2048]; /* static line buffer */ while (flagTerminate == FALSE) { printf(">"); /* this is our prompt */ pszLine = gets(pszLineBuffer); /* now get the command line */ StrTrim(pszLine); /* remove excess characters */ /* our simple command dispatcher */ if (strnicmp("LOAD", pszLine, 4) == 0) { PSZ pszModule = pszLine + 5; StrTrim(pszModule); /* load the module with some profiling */ rc = LoadModulePerf(pszModule, NULL); } else if (strnicmp("QUIT", pszLine, 4) == 0) { flagTerminate = TRUE; } else if (strnicmp("EXIT", pszLine, 4) == 0) { flagTerminate = TRUE; } else if (strnicmp("HELP", pszLine, 4) == 0) { printf("\nKnown commands:\n" " LOAD [module name]\n" " HELP\n" " QUIT, EXIT\n"); } // ... else printf("Unknown command.\n"); } return NO_ERROR; }
int SplitStringInfo(const TCHAR *szWholeText, TCHAR *szStartText, TCHAR *szEndText) { const TCHAR *pos = _tcschr(szWholeText, '|'); if (pos) { size_t index = pos - szWholeText; lstrcpyn(szStartText, szWholeText, (int)index); szStartText[index] = '\0'; StrTrim(szStartText, _T(" ")); lstrcpyn(szEndText, pos + 1, (int)_tcslen(pos)); //copies the \0 as well ... :) StrTrim(szEndText, _T(" ")); } else szStartText[0] = szEndText[0] = '\0'; return 0; }
bool CPreviewPlugin::Execute(LPCTSTR szCommand) { TCHAR szFile[ MAX_PATH ] = {}; lstrcpyn( szFile, szCommand, _countof( szFile ) ); PathRemoveArgs( szFile ); TCHAR szParameters[ MAX_PATH * 2 ] = {}; lstrcpyn( szParameters, szCommand + lstrlen( szFile ), _countof( szParameters ) ); StrTrim( szParameters, _T(" \t") ); PathUnquoteSpaces( szFile ); // Launch new process SHELLEXECUTEINFO sei = { sizeof( SHELLEXECUTEINFO ), SEE_MASK_NOCLOSEPROCESS, GetDesktopWindow(), NULL, szFile, szParameters, NULL, SW_SHOWNORMAL }; if ( ! ShellExecuteEx( &sei ) ) return false; // Wait for process exit m_hProcess.Attach( sei.hProcess ); WaitForSingleObject( sei.hProcess, INFINITE ); m_hProcess.Close(); return true; }
/** Parses a stream of the form # Comment key1 = value1 key2 = value2 \param[in] configuration Stream with configuration data. Typically as read from a configuration file. */ void ConfigurationParser::ParseStream(std::wistream& configuration) { SCXCoreLib::SCXLogHandle log = SCXLogHandleFactory::GetLogHandle(L"scx.core.providers.runasprovider.configparser"); std::vector<std::wstring> lines; SCXStream::NLFs nlfs; SCXStream::ReadAllLines(configuration, lines, nlfs); SCX_LOGTRACE(log, StrAppend(L"Number of lines in configuration: ", lines.size())); for (std::vector<std::wstring>::const_iterator it = lines.begin(); it != lines.end(); it++) { std::wstring line = StrTrim(*it); SCX_LOGTRACE(log, StrAppend(L"Parsing line: ", line)); if (line.length() == 0 || line.substr(0,1) == L"#") //comment { continue; } std::vector<std::wstring> parts; StrTokenize(line, parts, L"="); if (parts.size() == 2) { iterator iter = lower_bound(parts[0]); if ((end() != iter) && !(key_comp()(parts[0], iter->first))) { iter->second = parts[1]; } else { insert(iter, std::pair<const std::wstring, std::wstring>(parts[0], parts[1])); } } } }
void Utilities_String_Trim(void* State) { char* StrValue = State_PopString(State); char* TrmValue = StrTrim(StrValue); free(StrValue); State_PushString(State, TrmValue); };
/* * Discards comments, (delimited by ; and to the left of " if present) * Throws out initial whitespace, trailing whitespace and whitespace * between the = lines * Whitespace includes CR and LF characters. */ static int VarTrim (char *buf) { char *p, *q; /* Make sure we have an =, otherwise we might as well bail */ if ((p = strchr(buf, '=')) == NULL) return (0); if (!CmtTrim(buf)) return (0); if (!StrTrim(buf)) return (0); /* Remove white space after = */ if ((p = strchr(buf, '=')) != NULL) { p++; q = p; while (isspace((int)*q)) q++; if (p != q) memmove (p, q, strlen(q)+1); } /* Remove white space before = */ if ((p = q = strchr(buf, '=')) != NULL) { if (q != buf) { while (((p-1) >= buf) && isspace((int)*(p-1))) p--; if (p != q) memmove(p, q, strlen(q)+1); } } if (strlen(buf) > 0) return (1); return (0); }
DWORD WINAPI HashVerifyThread( PTSTR pszPath ) { // We will need to free the memory allocated for the data when done PBYTE pbRawData; // First, activate our manifest and AddRef our host ULONG_PTR uActCtxCookie = ActivateManifest(TRUE); ULONG_PTR uHostCookie = HostAddRef(); // Allocate the context data that will persist across this session HASHVERIFYCONTEXT hvctx; // It's important that we zero the memory since an initial value of zero is // assumed for many of the elements ZeroMemory(&hvctx, sizeof(hvctx)); // Prep the path HashNormalizeString(pszPath); StrTrim(pszPath, TEXT(" ")); hvctx.pszPath = pszPath; // Load the raw data pbRawData = HashVerifyLoadData(&hvctx); if (hvctx.pszFileData && (hvctx.hList = SLCreateEx(TRUE))) { HashVerifyParseData(&hvctx); DialogBoxParam( g_hModThisDll, MAKEINTRESOURCE(IDD_HASHVERF), NULL, HashVerifyDlgProc, (LPARAM)&hvctx ); SLRelease(hvctx.hList); } else if (*pszPath) { // Technically, we could reach this point by either having a file read // error or a memory allocation error, but I really don't feel like // doing separate messages for what are supposed to be rare edge cases. TCHAR szFormat[MAX_STRINGRES], szMessage[0x100]; LoadString(g_hModThisDll, IDS_HV_LOADERROR_FMT, szFormat, countof(szFormat)); wnsprintf(szMessage, countof(szMessage), szFormat, pszPath); MessageBox(NULL, szMessage, NULL, MB_OK | MB_ICONERROR); } free(pbRawData); free(pszPath); // Clean up the manifest activation and release our host DeactivateManifest(uActCtxCookie); HostRelease(uHostCookie); InterlockedDecrement(&g_cRefThisDll); return(0); }
PTSTR WINAPI PrepPath( PTSTR pszPath ) { // Appending a semicolon to the strings not only make their joining a bit // easier, but it also ensures that when determining if a path already // exists, the search will not be affected by subpath matches StrTrim(pszPath, TEXT(" \t;")); StrCatBuff(pszPath, TEXT(";"), CCHMAX_BUFFER); return(pszPath); }
static int ReadStatusFile (statusfile_t *sf) { FILE *fp; char *section = NULL, *new_section = NULL; char buf[BUFSIZE]; int length; int ret = 0; int c; if ((fp = fopen (sf->filename, "r")) != NULL) { while (fgets (buf, BUFSIZE, fp) != NULL) { length = strlen (buf); if (((length >= 1) && (buf[length - 1] == '\n')) || ((length >= 2) && (buf[length - 1] == '\r') && (buf[length - 2] == '\n'))) { /* Canonicalize on Unix style EOL */ if ((new_section = IsSection(buf)) != NULL) { if (section) free(section); section = new_section; } else { if (!ProcessLine(sf, section, buf)) { /* Ignore blank lines */ if (StrTrim(buf)) trace(INFO, default_trace, "ERROR: Failed to process line [%s]\n", buf); } } continue; } else { StrTrim(buf); trace (INFO, default_trace, "ERROR: Overflowed line for statusfile %s [%s]\n", sf->filename, buf); do { c = fgetc(fp); } while ((c != '\n') && (c != EOF)); if (c == EOF) break; continue; } } ret = 1; } return (ret); }
int WinRun4J::DoBuiltInCommand(HINSTANCE hInstance, LPSTR lpCmdLine) { // Remove any leading whitespace StrTrim(lpCmdLine, " "); // Make sure we also log to console Log::SetLogFileAndConsole(true); // Check for RegisterDDE util request if(StartsWith(lpCmdLine, "--WinRun4J:RegisterFileAssociations")) { DDE::RegisterFileAssociations(WinRun4J::LoadIniFile(hInstance), lpCmdLine); return 0; } // Check for UnregisterDDE util request if(StartsWith(lpCmdLine, "--WinRun4J:UnregisterFileAssociations")) { DDE::UnregisterFileAssociations(WinRun4J::LoadIniFile(hInstance), lpCmdLine); return 0; } // Check for Register Service util request if(StartsWith(lpCmdLine, "--WinRun4J:RegisterService")) { dictionary* ini = INI::LoadIniFile(hInstance); if(ini == NULL) return 1; Service::Register(ini); return 0; } // Check for Unregister Service util request if(StartsWith(lpCmdLine, "--WinRun4J:UnregisterService")) { dictionary* ini = INI::LoadIniFile(hInstance); if(ini == NULL) return 1; Service::Unregister(ini); return 0; } if(StartsWith(lpCmdLine, "--WinRun4J:PrintINI")) { dictionary* ini = INI::LoadIniFile(hInstance); if(ini == NULL) return 1; for(int i = 0; i < ini->n; i++) printf("%s=%s\n", ini->key[i], ini->val[i]); return 0; } if(StartsWith(lpCmdLine, "--WinRun4J:ExecuteINI")) { return WinRun4J::ExecuteINI(hInstance, lpCmdLine); } Log::Error("Unrecognized command: %s", lpCmdLine); return 1; }
static void changeText(CMFCEditBrowseCtrl &ctrl, LPTSTR text) { static const int bsize = AnalyticalFileChooser::bufSize; static TCHAR tmpBuf[bsize]; static int textLen; static BOOL change; textLen = ctrl.GetWindowTextLengthW(); ctrl.GetWindowTextW(tmpBuf, bsize); StrTrim(tmpBuf, _T(" \t")); lstrcpynW(text, tmpBuf, bsize); }
static BOOL checkTextModify(CMFCEditBrowseCtrl &ctrl, LPTSTR text) { static const int bsize = AnalyticalFileChooser::bufSize; static TCHAR tmpBuf[bsize]; static int textLen; static BOOL change; textLen = ctrl.GetWindowTextLengthW(); ctrl.GetWindowTextW(tmpBuf, bsize); StrTrim(tmpBuf, _T(" \t")); change = 0 == memcmp(tmpBuf, text, textLen * sizeof(TCHAR)) ? FALSE : TRUE; /*if (change) lstrcpynW(text, tmpBuf, bsize);*/ return change; }
/** * @brief Wrap Merge7z::GuessFormat() to allow for some customizing: * - Check if 7-Zip integration is enabled. * - Check for filename extension mappings. */ Merge7z::Format *ArchiveGuessFormat(LPCTSTR path) { if (GetOptionsMgr()->GetInt(OPT_ARCHIVE_ENABLE) == 0) return NULL; if (PathIsDirectory(path)) return NULL; // Map extensions through ExternalArchiveFormat.ini static TCHAR null[] = _T(""); static const TCHAR section[] = _T("extensions"); LPCTSTR entry = PathFindExtension(path); TCHAR value[20]; static LPCTSTR filename = NULL; if (filename == NULL) { TCHAR cPath[INTERNET_MAX_PATH_LENGTH]; DWORD cchPath = SearchPath(NULL, _T("ExternalArchiveFormat.ini"), NULL, INTERNET_MAX_PATH_LENGTH, cPath, NULL); filename = cchPath && cchPath < INTERNET_MAX_PATH_LENGTH ? StrDup(cPath) : null; } if (*filename && GetPrivateProfileString(section, entry, null, value, 20, filename) && *value == '.') { // Remove end-of-line comments (in string returned from GetPrivateProfileString) // that is, remove semicolon & whatever follows it if (LPTSTR p = StrChr(value, ';')) { *p = '\0'; StrTrim(value, _T(" \t")); } path = value; } // PATCH [ 1229867 ] RFE [ 1205516 ], RFE [ 887948 ], and other issues // command line integration portion is not yet applied // so following code not yet valid, so temporarily commented out // Look for command line tool first /*Merge7z::Format *pFormat; if (CExternalArchiveFormat::GuessFormat(path, pFormat)) { return pFormat; }*/ // Default to Merge7z*.dll return Merge7z->GuessFormat(path); }
/* * The providers arg is a CSV of section names pointing to settings for each server */ void ParseProviders(char* providers) { char section[MAX_PATH]; for(int i = 0, pos = 0;; i++) { char c = providers[i]; if(c == 0 || c == ',') { int len = i - pos; memcpy(section, &providers[pos], len); section[len] = 0; StrTrim(section, " "); g_serverSections[g_serverCount++] = strdup(section); pos = i + 1; } if(c == 0 || g_serverCount == MAX_SERVERS) break; } }
char *esEncMem(const void * const str, unsigned len) { byte *s, *p; const byte *q; unsigned ch; assert(str); /* At maximum each characters is transformed into two bytes */ if((p = s = emalloc(2 * len + 2)) == 0) return 0; for(q = str; len-- && (ch = *p++ = *q++) != 0;) if(ch < 32) { p[-1] = ES_CLEAR_HIGH; *p++ = ch | 0x80; } *p = 0; return StrTrim(s); }
APIRET LoadModulesFromListFile(PSZ pszModuleList) { PSZ pszLine; /* returned line from file */ int rc; /* operation return code */ char pszLineBuffer[512]; /* static line buffer */ FILE *fileList = fopen(pszModuleList, "r"); // check if file could be opened if (NULL == fileList) return ERROR_FILE_NOT_FOUND; // read lines until end of file for(;;) { // read line from file pszLine = fgets(pszLineBuffer, sizeof(pszLineBuffer), fileList); // done ? if (NULL == pszLine) break; else { // remove trailing CRLF StrTrim(pszLine); // load the specified module rc = LoadModule(pszLine, NULL); if (rc == NO_ERROR) /* check for errors */ printf("%s : loaded\n", pszLine); else printf("%s : failed with error %u.\n", pszLine, rc); } } return NO_ERROR; /* OK */ }
void CDlgSetRDPPort::OnChangeEditNewPort() { TCHAR szOrgPort[ MAX_PATH ]; TCHAR szNewPort[ MAX_PATH ]; memset( szOrgPort, 0, sizeof(szOrgPort) ); memset( szNewPort, 0, sizeof(szNewPort) ); m_editOrgPort.GetWindowText( szOrgPort, sizeof(szOrgPort) ); m_editNewPort.GetWindowText( szNewPort, sizeof(szNewPort) ); StrTrim( szNewPort, "\r\n\t " ); if ( CProcFunc::IsValidPortNumber( szNewPort ) && 0 != _tcsicmp( szOrgPort, szNewPort ) ) { m_btnSave.EnableWindow( TRUE ); } else { m_btnSave.EnableWindow( FALSE ); } }
BOOL CDlgSetRDPPort::SaveConfig() { BOOL bRet = FALSE; TCHAR szNewPort[ MAX_PATH ]; DWORD dwNewPort; BOOL bAddToFwException; CProcWinFirewall cProcFw; HRESULT hr; BOOL bFwIsOn; DWORD dwSetValue; // ... bRet = FALSE; memset( szNewPort, 0, sizeof(szNewPort) ); m_editNewPort.GetWindowText( szNewPort, sizeof(szNewPort) ); StrTrim( szNewPort, "\r\n\t " ); dwNewPort = (DWORD)StrToInt( szNewPort ); if ( CProcFunc::IsValidPortNumber( szNewPort ) && dwNewPort > 1024 && dwNewPort < 65535 ) { bAddToFwException = FALSE; // 添加端口到 Windows 防火墙的例外 if ( m_chkAddToFwException.GetCheck() ) { // 确认防火墙服务存在 if ( cProcFw.IsFwSrvExist() && SUCCEEDED( cProcFw.IsOn( &bFwIsOn ) ) ) { hr = cProcFw.PortAdd( dwNewPort, NET_FW_IP_PROTOCOL_TCP, L"Remote Desktop(VwFirewall)" ); if ( SUCCEEDED( hr ) ) { bAddToFwException = TRUE; } else { // 将端口(%d)添加到 Windows 防火墙时失败,请您手动添加后再试。 m_strCaption.Format( IDS_MSG_CAPTION_WARNING ); m_strString.Format( IDS_DLGSETRDPPORT_ERR_ADDPORT_EXP1, dwNewPort ); MessageBox( m_strString, m_strCaption, MB_ICONWARNING ); } } else { // 防火墙不存,无需添加,所以算成功 bAddToFwException = TRUE; } } else { // 用户未选择,算成功 bAddToFwException = TRUE; } if ( bAddToFwException ) { // // 保存到注册表 // dwSetValue = SHSetValue ( HKEY_LOCAL_MACHINE, _T("SYSTEM\\CurrentControlSet\\Control\\Terminal Server\\Wds\\rdpwd\\Tds\\tcp"), _T("PortNumber"), REG_DWORD, (LPCVOID)(&dwNewPort), sizeof(dwNewPort) ); if ( ERROR_SUCCESS == dwSetValue ) { dwSetValue = SHSetValue ( HKEY_LOCAL_MACHINE, _T("SYSTEM\\CurrentControlSet\\Control\\Terminal Server\\WinStations\\RDP-Tcp"), _T("PortNumber"), REG_DWORD, (LPCVOID)(&dwNewPort), sizeof(dwNewPort) ); if ( ERROR_SUCCESS == dwSetValue ) { bRet = TRUE; } } if ( ! bRet ) { // 保存端口(%d)时失败,请确认注册表允许修改,或者关闭相关病毒保护软件后再试。 m_strCaption.Format( IDS_MSG_CAPTION_WARNING ); m_strString.Format( IDS_DLGSETRDPPORT_ERR_ADDPORT_EXP2, dwNewPort ); MessageBox( m_strString, m_strCaption, MB_ICONWARNING ); } } } else { // 请输入正确的端口号,必须是 1024 至 65535 之间的数字。 m_strCaption.Format( IDS_MSG_CAPTION_WARNING ); m_strString.Format( IDS_DLGSETRDPPORT_ERR_ADDPORT_EXP3 ); MessageBox( m_strString, m_strCaption, MB_ICONWARNING ); } return bRet; }
/** Find out operating system name and version This method caches system information in m_osName, m_osVersion and m_osAlias. It requires m_unameInfo to be set prior to call. */ void SCXOSTypeInfo::Init() // private { m_osVersion = L""; m_osName = L"Unknown"; assert(m_unameIsValid); #if defined(hpux) || defined(sun) if (m_unameIsValid) { m_osName = StrFromMultibyte(m_unameInfo.sysname); m_osVersion = StrFromMultibyte(m_unameInfo.release); } #if defined(hpux) m_osAlias = L"HPUX"; #elif defined(sun) m_osAlias = L"Solaris"; #endif #elif defined(aix) if (m_unameIsValid) { m_osName = StrFromMultibyte(m_unameInfo.sysname); // To get "5.3" we must read "5" and "3" from different fields. string ver(m_unameInfo.version); ver.append("."); ver.append(m_unameInfo.release); m_osVersion = StrFromMultibyte(ver); } m_osAlias = L"AIX"; #elif defined(linux) vector<wstring> lines; SCXStream::NLFs nlfs; #if defined(PF_DISTRO_SUSE) static const string relFileName = "/etc/SuSE-release"; wifstream relfile(relFileName.c_str()); wstring version(L""); wstring patchlevel(L""); SCXStream::ReadAllLines(relfile, lines, nlfs); if (!lines.empty()) { m_osName = ExtractOSName(lines[0]); } // Set the Linux Caption (get first line of the /etc/SuSE-release file) m_linuxDistroCaption = lines[0]; if (0 == m_linuxDistroCaption.length()) { // Fallback - should not normally happen m_linuxDistroCaption = L"SuSE"; } // File contains one or more lines looking like this: // SUSE Linux Enterprise Server 10 (i586) // VERSION = 10 // PATCHLEVEL = 1 for (size_t i = 0; i<lines.size(); i++) { if (StrIsPrefix(StrTrim(lines[i]), L"VERSION", true)) { wstring::size_type n = lines[i].find_first_of(L"="); if (n != wstring::npos) { version = StrTrim(lines[i].substr(n+1)); } } else if (StrIsPrefix(StrTrim(lines[i]), L"PATCHLEVEL", true)) { wstring::size_type n = lines[i].find_first_of(L"="); if (n != wstring::npos) { patchlevel = StrTrim(lines[i].substr(n+1)); } } } if (version.length() > 0) { m_osVersion = version; if (patchlevel.length() > 0) { m_osVersion = version.append(L".").append(patchlevel); } } if (std::wstring::npos != m_osName.find(L"Desktop")) { m_osAlias = L"SLED"; } else { // Assume server. m_osAlias = L"SLES"; } #elif defined(PF_DISTRO_REDHAT) static const string relFileName = "/etc/redhat-release"; wifstream relfile(relFileName.c_str()); SCXStream::ReadAllLines(relfile, lines, nlfs); if (!lines.empty()) { m_osName = ExtractOSName(lines[0]); } // Set the Linux Caption (get first line of the /etc/redhat-release file) m_linuxDistroCaption = lines[0]; if (0 == m_linuxDistroCaption.length()) { // Fallback - should not normally happen m_linuxDistroCaption = L"Red Hat"; } // File should contain one line that looks like this: // Red Hat Enterprise Linux Server release 5.1 (Tikanga) if (lines.size() > 0) { wstring::size_type n = lines[0].find_first_of(L"0123456789"); if (n != wstring::npos) { wstring::size_type n2 = lines[0].substr(n).find_first_of(L" \t\n\t"); m_osVersion = StrTrim(lines[0].substr(n,n2)); } } if ((std::wstring::npos != m_osName.find(L"Client")) // RHED5 || (std::wstring::npos != m_osName.find(L"Desktop"))) // RHED4 { m_osAlias = L"RHED"; } else { // Assume server. m_osAlias = L"RHEL"; } #elif defined(PF_DISTRO_UBUNTU) static const string relFileName = "/etc/lsb-release"; wifstream relfile(relFileName.c_str()); wstring version(L""); wstring patchlevel(L""); SCXStream::ReadAllLines(relfile, lines, nlfs); // File contains one or more lines looking like this: // DISTRIB_ID=Ubuntu // DISTRIB_RELEASE=6.06 // DISTRIB_CODENAME=dapper // DISTRIB_DESCRIPTION="Ubuntu 6.06.2 LTS" for (size_t i = 0; i<lines.size(); i++) { if (StrIsPrefix(StrTrim(lines[i]), L"DISTRIB_DESCRIPTION", true)) { wstring::size_type n = lines[i].find_first_of(L"\""); if (n != wstring::npos) { // Strip the quote (") characters ... m_osName = StrTrim(lines[i].substr(n+1)); m_osName = m_osName.erase(m_osName.length()-1); // This is an alias on Ubuntu (and not used for SCX_STACK_ONLY) m_linuxDistroCaption = m_osName; } } } if (! m_osName.empty()) { wstring::size_type n = m_osName.find_first_of(L"0123456789"); if (n != wstring::npos) { wstring::size_type n2 = m_osName.substr(n).find_first_of(L" \t\n\t"); m_osVersion = StrTrim(m_osName.substr(n,n2)); } m_osName = ExtractOSName(m_osName); } m_osAlias = L"Ubuntu"; #else #error "Linux Platform not supported" #endif #elif defined(macos) m_osAlias = L"MacOS"; if (m_unameIsValid) { // MacOS is called "Darwin" in uname info, so we hard-code here m_osName = L"Mac OS"; // This value we could read dynamically from the xml file // /System/Library/CoreServices/SystemVersion.plist, but that // file may be named differently based on client/server, and // reading the plist file would require framework stuff. // // Rather than using the plist, we'll use Gestalt, which is an // API designed to figure out versions of anything and everything. // Note that use of Gestalt requires the use of framework stuff // as well, so the Makefiles for MacOS are modified for that. SInt32 major, minor, bugfix; if (0 != Gestalt(gestaltSystemVersionMajor, &major) || 0 != Gestalt(gestaltSystemVersionMinor, &minor) || 0 != Gestalt(gestaltSystemVersionBugFix, &bugfix)) { throw SCXCoreLib::SCXErrnoException(L"Gestalt", errno, SCXSRCLOCATION); } wostringstream sout; sout << major << L"." << minor << L"." << bugfix; m_osVersion = sout.str(); } #else #error "Platform not supported" #endif }
/** * ParseLineArgV * * Parses and processes a line which was sent by the server. * * @param argc number of tokens * @param argv the tokens */ bool CIRCConnection::ParseLineArgV(int argc, const char **argv) { CChannel *Channel; CClientConnection *Client; m_LastResponse = g_CurrentTime; if (argc < 2) { return true; } const char *Reply = argv[0]; const char *Raw = argv[1]; char *Nick = ::NickFromHostmask(Reply); int iRaw = atoi(Raw); bool b_Me = false; if (m_CurrentNick != NULL && Nick != NULL && strcasecmp(Nick, m_CurrentNick) == 0) { b_Me = true; } free(Nick); Client = GetOwner()->GetClientConnectionMultiplexer(); // HASH values CHashCompare hashRaw(argv[1]); static CHashCompare hashPrivmsg("PRIVMSG"); static CHashCompare hashNotice("NOTICE"); static CHashCompare hashJoin("JOIN"); static CHashCompare hashPart("PART"); static CHashCompare hashKick("KICK"); static CHashCompare hashNick("NICK"); static CHashCompare hashQuit("QUIT"); static CHashCompare hashMode("MODE"); static CHashCompare hashTopic("TOPIC"); static CHashCompare hashPong("PONG"); // END of HASH values if (argc > 3 && iRaw == 433) { bool ReturnValue = ModuleEvent(argc, argv); if (ReturnValue) { if (GetCurrentNick() == NULL) { WriteLine("NICK :%s_", argv[3]); } if (m_NickCatchTimer == NULL) { m_NickCatchTimer = new CTimer(30, false, NickCatchTimer, this); } } return ReturnValue; } else if (argc > 3 && hashRaw == hashPrivmsg && Client == NULL) { const char *Host; const char *Dest = argv[2]; char *Nick = ::NickFromHostmask(Reply); Channel = GetChannel(Dest); if (Channel != NULL) { CNick *User = Channel->GetNames()->Get(Nick); if (User != NULL) { User->SetIdleSince(g_CurrentTime); } Channel->AddBacklogLine(argv[0], argv[3]); } if (!ModuleEvent(argc, argv)) { free(Nick); return false; } /* don't log ctcp requests */ if (argv[3][0] != '\1' && argv[3][strlen(argv[3]) - 1] != '\1' && Dest != NULL && Nick != NULL && m_CurrentNick != NULL && strcasecmp(Dest, m_CurrentNick) == 0 && strcasecmp(Nick, m_CurrentNick) != 0) { char *Dup; char *Delim; Dup = strdup(Reply); if (AllocFailed(Dup)) { free(Nick); return true; } Delim = strchr(Dup, '!'); if (Delim != NULL) { *Delim = '\0'; Host = Delim + 1; } GetOwner()->Log("%s (%s): %s", Dup, Delim ? Host : "<unknown host>", argv[3]); free(Dup); } free(Nick); UpdateHostHelper(Reply); return true; } else if (argc > 3 && hashRaw == hashPrivmsg && Client != NULL) { Channel = GetChannel(argv[2]); if (Channel != NULL) { Channel->AddBacklogLine(argv[0], argv[3]); } } else if (argc > 3 && hashRaw == hashNotice && Client == NULL) { const char *Dest = argv[2]; char *Nick; if (!ModuleEvent(argc, argv)) { return false; } Nick = ::NickFromHostmask(Reply); /* don't log ctcp replies */ if (argv[3][0] != '\1' && argv[3][strlen(argv[3]) - 1] != '\1' && Dest != NULL && Nick != NULL && m_CurrentNick != NULL && strcasecmp(Dest, m_CurrentNick) == 0 && strcasecmp(Nick, m_CurrentNick) != 0) { GetOwner()->Log("%s (notice): %s", Reply, argv[3]); } free(Nick); return true; } else if (argc > 2 && hashRaw == hashJoin) { if (b_Me) { AddChannel(argv[2]); /* GetOwner() can be NULL if AddChannel failed */ if (GetOwner() != NULL && Client == NULL) { WriteLine("MODE %s", argv[2]); } } Channel = GetChannel(argv[2]); if (Channel != NULL) { Nick = NickFromHostmask(Reply); if (AllocFailed(Nick)) { return false; } Channel->AddUser(Nick, '\0'); free(Nick); } UpdateHostHelper(Reply); } else if (argc > 2 && hashRaw == hashPart) { bool bRet = ModuleEvent(argc, argv); if (b_Me) { RemoveChannel(argv[2]); } else { Channel = GetChannel(argv[2]); if (Channel != NULL) { Nick = ::NickFromHostmask(Reply); if (AllocFailed(Nick)) { return false; } Channel->RemoveUser(Nick); free(Nick); } } UpdateHostHelper(Reply); return bRet; } else if (argc > 3 && hashRaw == hashKick) { bool bRet = ModuleEvent(argc, argv); if (m_CurrentNick != NULL && strcasecmp(argv[3], m_CurrentNick) == 0) { RemoveChannel(argv[2]); if (Client == NULL) { char *Dup = strdup(Reply); if (AllocFailed(Dup)) { return bRet; } char *Delim = strchr(Dup, '!'); const char *Host = NULL; if (Delim) { *Delim = '\0'; Host = Delim + 1; } GetOwner()->Log("%s (%s) kicked you from %s (%s)", Dup, Delim ? Host : "<unknown host>", argv[2], argc > 4 ? argv[4] : ""); free(Dup); } } else { Channel = GetChannel(argv[2]); if (Channel != NULL) { Channel->RemoveUser(argv[3]); } } UpdateHostHelper(Reply); return bRet; } else if (argc > 2 && iRaw == 1) { if (Client != NULL) { if (strcmp(Client->GetNick(), argv[2]) != 0) { Client->WriteLine(":%s!%s NICK :%s", Client->GetNick(), m_Site ? m_Site : "*****@*****.**", argv[2]); } } free(m_CurrentNick); m_CurrentNick = strdup(argv[2]); free(m_Server); m_Server = strdup(Reply); } else if (argc > 2 && hashRaw == hashNick) { if (b_Me) { free(m_CurrentNick); m_CurrentNick = strdup(argv[2]); } Nick = NickFromHostmask(argv[0]); int i = 0; if (!b_Me && GetOwner()->GetClientConnectionMultiplexer() == NULL) { const char *AwayNick = GetOwner()->GetAwayNick(); if (AwayNick != NULL && strcasecmp(AwayNick, Nick) == 0) { WriteLine("NICK %s", AwayNick); } } while (hash_t<CChannel *> *ChannelHash = m_Channels->Iterate(i++)) { ChannelHash->Value->RenameUser(Nick, argv[2]); } free(Nick); } else if (argc > 1 && hashRaw == hashQuit) { bool bRet = ModuleEvent(argc, argv); Nick = NickFromHostmask(argv[0]); int i = 0; while (hash_t<CChannel *> *ChannelHash = m_Channels->Iterate(i++)) { ChannelHash->Value->RemoveUser(Nick); } free(Nick); return bRet; } else if (argc > 1 && (iRaw == 422 || iRaw == 376)) { int DelayJoin = GetOwner()->GetDelayJoin(); if (m_State != State_Connected) { const CVector<CModule *> *Modules = g_Bouncer->GetModules(); for (int i = 0; i < Modules->GetLength(); i++) { (*Modules)[i]->ServerLogon(GetOwner()->GetUsername()); } const char *ClientNick; if (Client != NULL) { ClientNick = Client->GetNick(); if (strcmp(m_CurrentNick, ClientNick) != 0) { Client->ChangeNick(m_CurrentNick); } } GetOwner()->Log("You were successfully connected to an IRC server."); g_Bouncer->Log("User %s connected to an IRC server.", GetOwner()->GetUsername()); } if (DelayJoin == 1) { m_DelayJoinTimer = g_Bouncer->CreateTimer(5, false, DelayJoinTimer, this); } else if (DelayJoin == 0) { JoinChannels(); } if (Client == NULL) { bool AppendTS = (GetOwner()->GetConfig()->ReadInteger("user.ts") != 0); const char *AwayReason = GetOwner()->GetAwayText(); if (AwayReason != NULL) { WriteLine(AppendTS ? "AWAY :%s (Away since the dawn of time)" : "AWAY :%s", AwayReason); } } const char *AutoModes = GetOwner()->GetAutoModes(); const char *DropModes = GetOwner()->GetDropModes(); if (AutoModes != NULL) { WriteLine("MODE %s +%s", GetCurrentNick(), AutoModes); } if (DropModes != NULL && Client == NULL) { WriteLine("MODE %s -%s", GetCurrentNick(), DropModes); } m_State = State_Connected; } else if (argc > 1 && strcasecmp(Reply, "ERROR") == 0) { if (strstr(Raw, "throttle") != NULL) { GetOwner()->ScheduleReconnect(120); } else { GetOwner()->ScheduleReconnect(5); } if (GetCurrentNick() != NULL && GetSite() != NULL) { g_Bouncer->LogUser(GetUser(), "Error received for user %s [%s!%s]: %s", GetOwner()->GetUsername(), GetCurrentNick(), GetSite(), argv[1]); } else { g_Bouncer->LogUser(GetUser(), "Error received for user %s: %s", GetOwner()->GetUsername(), argv[1]); } } else if (argc > 3 && iRaw == 465) { if (GetCurrentNick() != NULL && GetSite() != NULL) { g_Bouncer->LogUser(GetUser(), "G/K-line reason for user %s [%s!%s]: %s", GetOwner()->GetUsername(), GetCurrentNick(), GetSite(), argv[3]); } else { g_Bouncer->LogUser(GetUser(), "G/K-line reason for user %s: %s", GetOwner()->GetUsername(), argv[3]); } } else if (argc > 5 && iRaw == 351) { free(m_ServerVersion); m_ServerVersion = strdup(argv[3]); free(m_ServerFeat); m_ServerFeat = strdup(argv[5]); } else if (argc > 3 && iRaw == 5) { for (int i = 3; i < argc - 1; i++) { char *Dup = strdup(argv[i]); if (AllocFailed(Dup)) { return false; } char *Eq = strchr(Dup, '='); if (strcasecmp(Dup, "NAMESX") == 0) { WriteLine("PROTOCTL NAMESX"); } char *Value; if (Eq) { *Eq = '\0'; Value = strdup(++Eq); } else { Value = strdup(""); } m_ISupport->Add(Dup, Value); free(Dup); } } else if (argc > 4 && iRaw == 324) { Channel = GetChannel(argv[3]); if (Channel != NULL) { Channel->ClearModes(); Channel->ParseModeChange(argv[0], argv[4], argc - 5, &argv[5]); Channel->SetModesValid(true); } } else if (argc > 3 && hashRaw == hashMode) { Channel = GetChannel(argv[2]); if (Channel != NULL) { Channel->ParseModeChange(argv[0], argv[3], argc - 4, &argv[4]); } else if (strcmp(m_CurrentNick, argv[2]) == 0) { bool Flip = true, WasNull; const char *Modes = argv[3]; size_t Length = strlen(Modes) + 1; if (m_Usermodes != NULL) { Length += strlen(m_Usermodes); } WasNull = (m_Usermodes != NULL) ? false : true; m_Usermodes = (char *)realloc(m_Usermodes, Length); if (AllocFailed(m_Usermodes)) { return false; } if (WasNull) { m_Usermodes[0] = '\0'; } while (*Modes != '\0') { if (*Modes == '+') { Flip = true; } else if (*Modes == '-') { Flip = false; } else { if (Flip) { size_t Position = strlen(m_Usermodes); m_Usermodes[Position] = *Modes; m_Usermodes[Position + 1] = '\0'; } else { char *CurrentModes = m_Usermodes; size_t a = 0; while (*CurrentModes != '\0') { *CurrentModes = m_Usermodes[a]; if (*CurrentModes != *Modes) { CurrentModes++; } a++; } } } Modes++; } } UpdateHostHelper(Reply); } else if (argc > 4 && iRaw == 329) { Channel = GetChannel(argv[3]); if (Channel != NULL) { Channel->SetCreationTime(atoi(argv[4])); } } else if (argc > 4 && iRaw == 332) { Channel = GetChannel(argv[3]); if (Channel != NULL) { Channel->SetTopic(argv[4]); } } else if (argc > 5 && iRaw == 333) { Channel = GetChannel(argv[3]); if (Channel != NULL) { Channel->SetTopicNick(argv[4]); Channel->SetTopicStamp(atoi(argv[5])); } } else if (argc > 3 && iRaw == 331) { Channel = GetChannel(argv[3]); if (Channel != NULL) { Channel->SetNoTopic(); } } else if (argc > 3 && hashRaw == hashTopic) { Channel = GetChannel(argv[2]); if (Channel != NULL) { Channel->SetTopic(argv[3]); Channel->SetTopicStamp(g_CurrentTime); Channel->SetTopicNick(argv[0]); } UpdateHostHelper(Reply); } else if (argc > 5 && iRaw == 353) { Channel = GetChannel(argv[4]); if (Channel != NULL) { const char *nicks; const char **nickv; nicks = ArgTokenize(argv[5]); if (AllocFailed(nicks)) { return false; } nickv = ArgToArray(nicks); if (AllocFailed(nickv)) { ArgFree(nicks); return false; } int nickc = ArgCount(nicks); for (int i = 0; i < nickc; i++) { char *Nick = strdup(nickv[i]); char *BaseNick = Nick; if (AllocFailed(Nick)) { ArgFree(nicks); return false; } StrTrim(Nick, ' '); while (IsNickPrefix(*Nick)) { Nick++; } char *Modes = NULL; if (BaseNick != Nick) { Modes = (char *)malloc(Nick - BaseNick + 1); if (!AllocFailed(Modes)) { strmcpy(Modes, BaseNick, Nick - BaseNick + 1); } } Channel->AddUser(Nick, Modes); free(BaseNick); free(Modes); } ArgFreeArray(nickv); ArgFree(nicks); } } else if (argc > 3 && iRaw == 366) { Channel = GetChannel(argv[3]); if (Channel != NULL) { Channel->SetHasNames(); } } else if (argc > 9 && iRaw == 352) { const char *Ident = argv[4]; const char *Host = argv[5]; const char *Server = argv[6]; const char *Nick = argv[7]; const char *Realname = argv[9]; char *Mask; int rc = asprintf(&Mask, "%s!%s@%s", Nick, Ident, Host); if (!RcFailed(rc)) { UpdateHostHelper(Mask); UpdateWhoHelper(Nick, Realname, Server); free(Mask); } } else if (argc > 6 && iRaw == 367) { Channel = GetChannel(argv[3]); if (Channel != NULL) { Channel->GetBanlist()->SetBan(argv[4], argv[5], atoi(argv[6])); } } else if (argc > 3 && iRaw == 368) { Channel = GetChannel(argv[3]); if (Channel != NULL) { Channel->SetHasBans(); } } else if (argc > 3 && iRaw == 396) { free(m_Site); m_Site = strdup(argv[3]); if (AllocFailed(m_Site)) {} } else if (argc > 3 && hashRaw == hashPong && m_Server != NULL && strcasecmp(argv[2], m_Server) == 0 && m_EatPong) { m_EatPong = false; return false; } else if (argc > 3 && iRaw == 421) { m_FloodControl->Unplug(); return false; } if (GetOwner() != NULL) { return ModuleEvent(argc, argv); } else { return true; } }
STDMETHODIMP CPreviewPlugin::Preview2(/* [in] */ BSTR sSource, /* [in] */ BSTR sTarget) { m_bCancel = false; if ( ! sSource || ! sTarget ) return E_POINTER; if ( ! m_pSite ) return E_UNEXPECTED; // Get extension LPCTSTR szTargetExt = PathFindExtension( sTarget ); if ( ! *szTargetExt ) return E_INVALIDARG; // Load data CAtlMap< CString, CString > oData; LoadData( oData ); // Find command line for extension for ( POSITION pos = oData.GetStartPosition(); pos; ) { CString sExt, sCommand; oData.GetNextAssoc( pos, sExt, sCommand ); TCHAR szKey[ MAX_PATH ] = { _T(".") }; for ( LPCTSTR str = sExt.GetBuffer(); ; ++str ) { LPTSTR space = StrChr( str, _T(' ') ); if ( space ) *space = _T('\0'); lstrcpyn( szKey + 1, str, _countof( szKey ) - 1 ); StrTrim( szKey + 1, _T(". /t") ); if ( lstrcmpi( szKey, szTargetExt ) == 0 ) { // Found! sExt.ReleaseBuffer(); if ( sCommand.Replace( _T("%1"), sSource ) == 0 || sCommand.Replace( _T("%2"), sTarget ) == 0 ) // Invalid command line return E_INVALIDARG; m_pSite->SetProgressMessage( CComBSTR( sCommand ) ); m_pSite->SetProgressRange( 100 ); if ( ! Execute( sCommand ) ) // Can't launch external program return E_FAIL; m_pSite->SetProgressPosition( 100 ); // Check for resulting file if ( GetFileAttributes( sTarget ) == INVALID_FILE_ATTRIBUTES ) // No file (user canceled it) return S_FALSE; // Run it m_pSite->QueueDeleteFile( sTarget ); if ( ! m_bCancel ) m_pSite->ExecuteFile( sTarget ); return S_OK; } if ( ! space ) { sExt.ReleaseBuffer(); break; } str = space; } } return E_INVALIDARG; }
extern void _cdecl ParseCommandLine(LPSTR lpCmdLine, TCHAR** args, UINT& count, bool includeFirst) { // Bug fix here provided by [email protected] if (lpCmdLine == NULL || *lpCmdLine == 0) return; StrTrim(lpCmdLine, " "); int len = strlen(lpCmdLine); if (len == 0) { return; } //values positions (like java - startPos inclusive, endPos exclusive) int startPos[1024], endPos[1024]; //current index of value borders int currentIndex = -1; //if we are inside quotes so space/tab are no arg separators bool insideQuotes = false; //if we are between values so space/tab are arg separators bool insideArgSeparator = true; int i; //let's find value borders for (i = 0; i < len; i++) { char c = lpCmdLine[i]; if (c == ' ' || c == '\t') { //space is no arg separator in quotes if (insideQuotes) { continue; }; //ignore multiple arg separators if (insideArgSeparator) { continue; }; //it is first arg separator so save the end border of value endPos[currentIndex] = i; //set we are in separator seeking mode insideArgSeparator = true; } else { if (insideArgSeparator) { //save start of value startPos[++currentIndex] = i; //set unknown end endPos[currentIndex] = -1; //set we are in value seeking mode insideArgSeparator = false; } if (c == '"') { insideQuotes = !insideQuotes; } } }//end of for(i = 0; i < len; i++) { if (endPos[currentIndex] < 0) { //set end position if it is still unknown endPos[currentIndex] = i; } int index = count; for (i = (includeFirst) ? 0 : 1; i <= currentIndex; i++) { int begin = startPos[i]; int end = endPos[i]; if (lpCmdLine[begin] == '"' && lpCmdLine[end - 1] == '"') { //remove quotes begin++; end--; } int valueLen = end - begin; if (valueLen > 0) { TCHAR *value = (TCHAR *)malloc(sizeof(TCHAR)* (valueLen + 1)); for (int a = 0; a < valueLen; a++) { value[a] = lpCmdLine[begin + a]; } value[valueLen] = '\0'; args[index++] = value; } } count = index; }
int Service::Initialise(dictionary* ini) { g_ini = ini; g_serviceId = iniparser_getstr(ini, SERVICE_ID); if (g_serviceId == NULL) { Log::Error("Service ID not specified"); return 1; } // Parse controls accepted char* controls = iniparser_getstr(ini, SERVICE_CONTROLS); if (controls) { int len = strlen(controls); int nb = 0; for (int i = 0; i < len; i++) { if (controls[i] == '|') { controls[i] = 0; nb++; } } char* p = controls; char* e = controls + len; for (int i = 0; i <= nb; i++) { int plen = strlen(p); StrTrim(p, " "); if (strcmp("stop", p) == 0) { g_controlsAccepted |= SERVICE_ACCEPT_STOP; } else if (strcmp("shutdown", p) == 0) { g_controlsAccepted |= SERVICE_ACCEPT_SHUTDOWN; } else if (strcmp("pause", p) == 0) { g_controlsAccepted |= SERVICE_ACCEPT_PAUSE_CONTINUE; } else if (strcmp("param", p) == 0) { g_controlsAccepted |= SERVICE_ACCEPT_PARAMCHANGE; } else if (strcmp("netbind", p) == 0) { g_controlsAccepted |= SERVICE_ACCEPT_NETBINDCHANGE; } else if (strcmp("hardware", p) == 0) { g_controlsAccepted |= SERVICE_ACCEPT_HARDWAREPROFILECHANGE; } else if (strcmp("power", p) == 0) { g_controlsAccepted |= SERVICE_ACCEPT_POWEREVENT; } else if (strcmp("session", p) == 0) { g_controlsAccepted |= SERVICE_ACCEPT_SESSIONCHANGE; } p += plen + 1; if (p >= e) break; } } else { g_controlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN; } // Initialise JNI members JNIEnv* env = VM::GetJNIEnv(); if (env == NULL) { Log::Error("JNIEnv is null"); return 1; } char* svcClass = iniparser_getstr(ini, SERVICE_CLASS); StrReplace(svcClass, '.', '/'); g_serviceClass = JNI::FindClass(env, svcClass); if (g_serviceClass == NULL) { Log::Error("Could not find service class"); return 1; } jmethodID scon = env->GetMethodID(g_serviceClass, "<init>", "()V"); if (scon == NULL) { Log::Error("Could not find service class default constructor"); return 1; } g_serviceInstance = env->NewObject(g_serviceClass, scon); if (g_serviceInstance == NULL) { Log::Error("Could not create service class"); return 1; } // Need a global reference here to as we transfer across threads g_serviceInstance = env->NewGlobalRef(g_serviceInstance); g_controlMethod = env->GetMethodID(g_serviceClass, "serviceRequest", "(I)I"); if (g_controlMethod == NULL) { Log::Error("Could not find control method class"); return 1; } g_mainMethod = env->GetMethodID(g_serviceClass, "serviceMain", "([Ljava/lang/String;)I"); if (g_mainMethod == NULL) { Log::Error("Could not find control main class"); return 1; } return 0; }
__forceinline UINT WINAPI EntryMain( UINT argc, PTSTR *argv, PBUFFER pBuffer ) { UINT uRetCode = 1; HKEY hKey = NULL; if (argc != 3 || (StrCmpI(argv[1], TEXT("pre")) && StrCmpI(argv[1], TEXT("post"))) || argv[2][0] == 0) { MessageBox( NULL, TEXT("Usage:\naddpath pre \"path\"\naddpath post \"path\""), TEXT("Usage Error"), MB_OK | MB_ICONWARNING ); return(~0); } if ( RegOpenKeyEx(HKEY_LOCAL_MACHINE, REGSTR_ENV, 0, KEY_QUERY_VALUE | KEY_SET_VALUE, &hKey) == ERROR_SUCCESS && hKey != NULL ) { DWORD cbBuffer = sizeof(pBuffer->szOld); DWORD dwType; StrCpyN(pBuffer->szNew, argv[2], CCHMAX_BUFFER); if ( RegQueryValueEx(hKey, TEXT("Path"), NULL, &dwType, (PBYTE)pBuffer->szOld, &cbBuffer) == ERROR_SUCCESS && cbBuffer >= 2 && (dwType == REG_SZ || dwType == REG_EXPAND_SZ) && StrStrI(PrepPath(pBuffer->szOld), PrepPath(pBuffer->szNew)) == NULL ) { PTSTR pszHead, pszTail; if (StrCmpI(argv[1], TEXT("pre")) == 0) { pszHead = pBuffer->szNew; pszTail = pBuffer->szOld; } else { pszHead = pBuffer->szOld; pszTail = pBuffer->szNew; } StrCatBuff(pszHead, pszTail, CCHMAX_BUFFER); StrTrim(pszHead, TEXT(";")); cbBuffer = (lstrlen(pszHead) + 1) * sizeof(TCHAR); if (RegSetValueEx(hKey, TEXT("Path"), 0, dwType, (PBYTE)pszHead, cbBuffer) == ERROR_SUCCESS) { SendMessageTimeout( HWND_BROADCAST, WM_SETTINGCHANGE, 0, (LPARAM)TEXT("Environment"), SMTO_ABORTIFHUNG, 5000, NULL ); uRetCode = 0; } else { uRetCode = 2; } } RegCloseKey(hKey); } return(uRetCode); }
/// Function name : translateXMLTagIntoNode // Description : Extract the name from an XML tag into an XMLTreeNode. Also extracts any property name/value pairs // and adds them to the XMLTreeNode's property list // // CONST TCHAR* szTag : [in] XML tag, optionally containing properties as awell as a name // CONST UINT iLength : [in] Length of XML tag, in characters // XML_TREE_NODE* pOutput : [in/out] Node to parse the properties into // VOID translateXMLTagIntoNode(CONST TCHAR* szTag, CONST UINT iLength, XML_TREE_NODE* pOutput) { XML_TAG_PARSE_STATE eState; // Current property parsing state XML_PROPERTY *pProperty; // Current property being parsed TCHAR *szTagCopy, // Copy of the input tag, for tokenising *szTokenEnd, // Pointer to the end of the current token *szToken; // Current token // Prepare eState = XTPS_PROPERTY_NAME; /// [JUST NAME] If tag contains no spaces then there is only the tag name if (utilFindCharacterInSet(szTag, " \r\n\t") == NULL) StringCchCopy(pOutput->szName, 24, szTag); /// [NAME and PROPERTIES] Extract the name and then parse the properties else { // Copy the input string (for tokenising) szTagCopy = utilDuplicateString(szTag, iLength); // Sever the tag name szTokenEnd = utilFindCharacter(szTagCopy, ' '); szTokenEnd[0] = NULL; /// [NAME] Store in the output node StringCchCopy(pOutput->szName, 24, szTagCopy); szToken = &szTokenEnd[1]; /// [PROPERTIES] Tokenise each property name and value manually (to avoid the "" (empty property) problem) // Reference: <sval type="array" size="18">, <sval type="int" val="703" /> for (szTokenEnd = utilFindCharacter(szToken, '"'); szTokenEnd; szTokenEnd = utilFindCharacter(szToken, '"')) { // Null terminate token szTokenEnd[0] = NULL; switch (eState) { /// [PROPERTY-NAME] Create a new property from the name case XTPS_PROPERTY_NAME: StrTrim(szToken, TEXT("= \t\r\n")); // Append new property to output node pProperty = createXMLProperty(szToken); appendPropertyToXMLTreeNode(pOutput, pProperty); // Switch to property values eState = XTPS_PROPERTY_VALUE; break; /// [VALUE] Store value in the current property case XTPS_PROPERTY_VALUE: pProperty->szValue = utilDuplicateSimpleString(szToken); // [CHECK] Replace any character entities if (utilFindSubString(pProperty->szValue, "&#")) performXMLCharacterEntityReplacement(pProperty->szValue, lstrlen(pProperty->szValue)); // Switch to property name eState = XTPS_PROPERTY_NAME; break; } // Move to next token szToken = &szTokenEnd[1]; } // Cleanup utilDeleteString(szTagCopy); } }
HRESULT CALLBACK modmap(PDEBUG_CLIENT4 Client, PCSTR Args) { HRESULT hRes; ULONG64 ModBase=0; ULONG ModSize; ULONG RemainderIndex; DEBUG_VALUE DebugValue = {}; INIT_API(); if (!Args || !*Args) { dprintf("[sync] !modmap <mod base> <mod size> <mod name>\n"); return E_FAIL; } /* msdn: Evaluate method evaluates an expression, returning the result. */ hRes=g_ExtControl->Evaluate(Args, DEBUG_VALUE_INT64, &DebugValue, &RemainderIndex); if(FAILED(hRes)) { dprintf("[sync] modmap: failed to evaluate module base\n"); return E_FAIL; } ModBase = (ULONG64)DebugValue.I64; Args += RemainderIndex; hRes=g_ExtControl->Evaluate(Args, DEBUG_VALUE_INT32, &DebugValue, &RemainderIndex); if(FAILED(hRes)) { dprintf("[sync] modmap: failed to evaluate module size\n"); return E_FAIL; } ModSize = (ULONG64)DebugValue.I32; Args += RemainderIndex; StrTrim((LPSTR)Args, " "); if (!*Args) { dprintf("[sync] modmap: failed to evaluate module name\n"); return E_FAIL; } /* msdn: The AddSyntheticModule method adds a synthetic module to the module list the debugger maintains for the current process. */ hRes=g_ExtSymbols3->AddSyntheticModule(ModBase, ModSize, Args, Args, DEBUG_ADDSYNTHMOD_DEFAULT); if(FAILED(hRes)) { dprintf("[sync] modmap: AddSyntheticModule failed\n"); return E_FAIL; } /* msdn: The AddSyntheticSymbol method adds a synthetic symbol to a module in the current process. */ hRes=g_ExtSymbols3->AddSyntheticSymbol(ModBase, ModSize, Args, DEBUG_ADDSYNTHSYM_DEFAULT, NULL); if(FAILED(hRes)) { dprintf("[sync] modmap: AddSyntheticSymbol failed\n"); hRes=g_ExtSymbols3->RemoveSyntheticModule(ModBase); return E_FAIL; } return hRes; }