Example #1
0
void GProfile::Load()
{
	if (m_bCached)
		return;

	// destroy the cached objects
	Destroy();

	char *szBuffer = 0;
	long dwSize = 0;



#ifdef _WIN32
	
		// open the file
		HANDLE hFile = CreateFile((const char *)m_strFile, 
								  GENERIC_READ, 0, 0, OPEN_EXISTING,
								  FILE_ATTRIBUTE_NORMAL, 0);

		dwSize = GetFileSize(hFile, NULL); 
 
		szBuffer = new char[dwSize + 1];

		// read the file
		long dwRead;
		if (!ReadFile(hFile, szBuffer, dwSize, (DWORD *)&dwRead, 0))
		{
			delete [] szBuffer;
			CloseHandle(hFile);
		}

		// close the file
		CloseHandle(hFile);


#else
	// open the file
	GString strTemp;
	int nResult = strTemp.FromFile((const char *)m_strFile, 0);

	szBuffer = new char[strTemp.Length() + 1];
	memcpy(szBuffer,(const char *)strTemp, strTemp.Length());
	dwSize = strTemp.Length();

#endif


	// terminate the buffer
	//szBuffer[dwSize] = 0;

	ProfileParse(szBuffer, dwSize);

	delete [] szBuffer;

}
Example #2
0
const char *GetThisEXEName()
{
	static GString strThisEXE;
	if (strThisEXE.Length())
		return strThisEXE;

	// get the path and file name of this .exe
	// the user may have renamed the exe 
	char pzName[512];
	memset(pzName,0,512);
	GetModuleFileName(NULL,pzName,512);

	// pick the file name off the end of the path
	int nLen = strlen(pzName);
	while (1)
	{
		nLen--;
		if (pzName[nLen] == '\\')
		{
			strThisEXE = &pzName[nLen+1];
			break;
		}
		if (nLen < 1)
			break;
	}
	// remove the extension, normally ".exe"
	strThisEXE.TrimRightBytes(4);

	return strThisEXE;
}
Example #3
0
void GProfile::SetConfigCipher(const char *szSection, const char *szEntry, const char *pzPassword, const char *lValue, int nValueLength)
{
	GString strDest;
	GString strErrorOut;
	GString strPass(pzPassword);
	EncryptMemoryToMemory(strPass, lValue,nValueLength,strDest, strErrorOut);
	SetConfigBinary(szSection, szEntry, (unsigned char *)strDest.Buf(), (int)strDest.Length());
}
Example #4
0
// Serialize memory config
// Returns the number of bytes written to the destination on success or 0 for failure.
long GProfile::WriteCurrentConfigHelper(const char *pzPathAndFileName, GString *pDest, const char *pzSection/*=0*/, bool bWriteXML/*=0*/)
{
	GString strLocalDest;
	GString *strConfigData = (pDest) ? pDest : &strLocalDest;

	try
	{
		if (bWriteXML)
		{
		    *strConfigData << "<configuration>";
		}

		GListIterator itSections(&m_lstSections);
		while ( itSections() )
		{
			GProfileSection *pSection = (GProfileSection *)itSections++;
			if (pzSection)
			{
				if( pSection->m_strName.CompareNoCase(pzSection) != 0)
				{
					continue;
				}
			}
			if (bWriteXML)
			{
				pSection->ToXML(strConfigData, 1);
			}
			else
			{
				(*strConfigData) << "[" << pSection->m_strName << "]\r\n";

				GListIterator itNVP(&pSection->m_lstNVP);
				while (itNVP())
				{
					GProfileEntry *pNVP = (GProfileEntry *)itNVP++;
					(*strConfigData) << pNVP->m_strName << "=" << pNVP->m_strValue << "\r\n";
				}
				if (itSections())
					(*strConfigData) << "\r\n\r\n";
			}
		}
		if (bWriteXML)
		{
		    *strConfigData << "\r\n</configuration>";
		}

		if (pzPathAndFileName)
			strConfigData->ToFile(pzPathAndFileName);

		return (long)strConfigData->Length();
	}
	catch(GException &)
	{
		// most likely due to invalid path or file name.
		return 0;	
	}
	return 0; // can't get here
}
Example #5
0
const char *GProfile::GetCiphered(const char *szSectionName, const char *szKey, const char *pzPassword, GString &strDest)
{
	GString strData;
	GetBinary(szSectionName, szKey, strData);
	GString strErrorOut;

	GString strPass(pzPassword);
	DecryptMemoryToMemory(strPass, strData, (int)strData.Length(), strDest, strErrorOut);
	return strDest;
}
Example #6
0
void GProfile::ProfileParse(const char *szBuffer, __int64 dwSize)
{
	GProfileSection *pSection = 0;

	// parse the file
	__int64 nIdx = 0;

	GString strLine;
	while (nIdx < dwSize)
	{
		GetLine(strLine, szBuffer, &nIdx, dwSize);

		strLine.TrimRightWS();
		strLine.TrimLeftWS();

		if ((strLine.IsEmpty()) || (strLine.GetAt(0) == ';'))
			continue;


		strLine.Replace("\\n", '\n');

		if (strLine.GetAt(0) == '[')
		{
			__int64 nIdx = strLine.Find(']');
			if (nIdx == -1)
				nIdx = strLine.Length();

			// new section
			pSection = new GProfileSection;
			pSection->m_strName = strLine.Mid(1, nIdx - 1);
			pSection->m_strName.TrimLeftWS();
			pSection->m_strName.TrimRightWS();

			m_lstSections.AddLast(pSection);
		}
		else if (pSection)
		{
			__int64 nIdx = strLine.Find('=');
			if (nIdx == -1)
				continue;
			GProfileEntry *pNVP = new GProfileEntry;
			pSection->m_lstNVP.AddLast(pNVP);
			pNVP->m_strName = strLine.Left(nIdx);
			pNVP->m_strName.TrimLeftWS();
			pNVP->m_strName.TrimRightWS();
			
			pNVP->m_strValue = strLine.Mid(nIdx + 1);
			pNVP->m_strValue.TrimLeftWS();
			pNVP->m_strValue.TrimRightWS();
		}
	}
	m_bCached = true;
}
Example #7
0
//-------------------------------------------------------------------------
//	get the string from a dialog text object
//-------------------------------------------------------------------------
Bool GWinDialog::GetDialogString(GString& String, int DialogItem)
{
	String.Chars().Resize(200);
	String.Chars()[0] = 0;
	
	if ( !GetDlgItemText( Hwnd(), DialogItem, String.Data(), String.Length() ) )
	{
		String.Clear();
		return FALSE;
	}

	return TRUE;
}
Example #8
0
extern "C" JNIEXPORT jint JNICALL Java_com_server_app_Server_serverStart  (JNIEnv *env, jobject obj, jstring s)
{
	int nRet = 0;
	env->GetJavaVM(&g_javaVM);
	jclass cls = env->GetObjectClass(obj);
	g_activityClass = (jclass) env->NewGlobalRef(cls);
	g_activityObj = env->NewGlobalRef(obj);

	if (!g_isRunning)
	{
		g_isRunning = 1;

		SetServerCoreInfoLog( JavaInfoLog );

		const char *str = env->GetStringUTFChars(s,0);
		GString g("Starting Server");
		JavaInfoLog(777, g);

		
		GStringList list("&&",str);
		GStringIterator it(&list);
		const char *p1 = it++;
		const char *p2 = it++;
		const char *p3 = it++;
		const char *p4 = it++;
		const char *p5 = it++;

		GString strCfgData;
		strCfgData.Format(pzBoundStartupConfig,p1,p2,p3,p4,p5);

		SetProfile(new GProfile((const char *)strCfgData, (int)strCfgData.Length(), 0));

		nRet = server_start("-- Android Server --");
		env->ReleaseStringUTFChars(s, str);

	}
	else
	{
		GString g("Server is already running");
		JavaInfoLog(777, g);
	}
	return nRet;
}
const char *GStringList::PeekFirst(__int64 *pnLen/* = 0*/)
{
	m_strSerializeDest = "";
	if (pnLen)
	{
		*pnLen = 0;
	}

	GString *pG = (GString *)GList::First();
	if (pG)
	{
		m_strSerializeDest = (const char *)*pG;
		if (pnLen)
		{
			*pnLen = pG->Length();
		}
	}
	return m_strSerializeDest;
}
Example #10
0
const char *GStringList::RemoveLast(__int64 *pnLen/* = 0*/)
{
	m_strSerializeDest = "";
	if (pnLen)
	{
		*pnLen = 0;
	}

	GString *pG = (GString *)GList::RemoveLast();
	if (pG)
	{
		m_strSerializeDest = (const char *)*pG;
		if (pnLen)
		{
			*pnLen = pG->Length();
		}
		delete pG;
	}
	return m_strSerializeDest;
}
Example #11
0
int WINAPI WinMain(HINSTANCE hinst, HINSTANCE hinstExePrev, 
   LPSTR pszCmdLine, int nCmdShow) {


	// ***** To debug this application  ****
	// set fDebug to 1, then recompile (in debug mode)
	// and run the program in a debugger like any windows .exe
	// The exact same code executes as if the user clicked the 
	// 'start' button in the NT services manager.
	int fDebug = 0;


   int nArgc = __argc;
#ifdef UNICODE
   LPCTSTR *ppArgv = (LPCTSTR*) CommandLineToArgvW(GetCommandLine(), &nArgc);
#else
   LPCTSTR *ppArgv = (LPCTSTR*) __argv;
#endif

   BOOL fStartService = (nArgc < 2);
   int i;

   int bInstall = 0;
   int bRemove  = 0;
   int bChange  = 0;
   GString  strPort("10888");

   GString strBoot;
   GString strRoot("NotUsed");
   for (i = 1; i < nArgc; i++) 
   {
      if ((ppArgv[i][0] == __TEXT('-')) || (ppArgv[i][0] == __TEXT('/'))) 
	  {
         // Command line switch
         if (lstrcmpi(&ppArgv[i][1], __TEXT("install")) == 0) 
            bInstall = 1;

         if (lstrcmpi(&ppArgv[i][1], __TEXT("remove"))  == 0)
            bRemove = 1;

         if (lstrcmpi(&ppArgv[i][1], __TEXT("change"))  == 0)
            bChange = 1;
		 

         GString strTemp(&ppArgv[i][1],strlen("desc:"));
		 if (strTemp.CompareNoCase("desc:") == 0)
		 {
            strServerDescription = &ppArgv[i][1+strlen("desc:")];
		 }

         GString strTemp2(&ppArgv[i][1],strlen("name:"));
		 if (strTemp2.CompareNoCase("name:") == 0)
		 {
            strServerName = &ppArgv[i][1+strlen("name:")];
		 }

         GString strTemp3(&ppArgv[i][1],strlen("pass:"******"pass:"******"pass:"******"boot:"));
		 if (strTemp4.CompareNoCase("boot:") == 0)
		 {
            strBoot = &ppArgv[i][1+strlen("boot:")];
		 }

         GString strTemp5(&ppArgv[i][1],strlen("port:"));
		 if (strTemp5.CompareNoCase("port:") == 0)
		 {
            strPort = &ppArgv[i][1+strlen("port:")];
		 }

         GString strTemp6(&ppArgv[i][1],strlen("root:"));
		 if (strTemp6.CompareNoCase("root:") == 0)
		 {
            strRoot = &ppArgv[i][1+strlen("root:")];
		 }
      }
   }

	if (bChange)
	{
		ModifyStartupFile(strBoot,strServerPassword,strRoot,strPort);
	}

	if (bInstall)
	{
		GString strThisEXEName(GetThisEXEName());


		// uuencode strBoot 
		BUFFER b;
		BufferInit(&b);
		uuencode((unsigned char *)(const char *)strBoot, (int)strBoot.Length(), &b);
		GString strEncodedBoot((char *)b.pBuf, b.cLen);
		BufferTerminate(&b);

		// open the registry, save the coded boot key, close the registry
		HKEY hk;
		if (RegCreateKey(HKEY_CLASSES_ROOT,(const char *)strThisEXEName,&hk) == ERROR_SUCCESS)
		{
			RegSetValue(hk,NULL,REG_SZ,(const char *)strEncodedBoot,0);
			RegCloseKey(hk);
		}

		// use root of file system to store the startup file 
		// unless specified otherwise by environment setting
		GString strOutFile("c:\\");
		strOutFile += strThisEXEName;
		if (getenv(strThisEXEName))
		{
			strOutFile += getenv(strThisEXEName);
		}
		
		
		// create the startup file
		GString strTempFile;
		strTempFile << strServerPassword << "&&" << strRoot << "&&" << strPort;
		strTempFile.ToFile("tempfile");
		GString strErrorOut;
		FileEncrypt(strBoot, "tempfile", strOutFile, strErrorOut);
		unlink("tempfile");


		InstallService();
	}
	if (bRemove)
	{
		RemoveService();

		GString strThisEXEName(GetThisEXEName());

		// remove the registry entry
		RegDeleteKey(HKEY_CLASSES_ROOT,(const char *)strThisEXEName);

		// remove the startup file
		GString strOutFile("c:\\");
		strOutFile += strThisEXEName;
		if (getenv(strThisEXEName))
		{
			strOutFile += getenv(strThisEXEName);
		}
		unlink(strOutFile);

	}

   strcpy(pzServer,strServerName);


   if (fDebug) 
   {
      // Running as EXE not as service, just run the service for debugging
	  TimeServiceMain(0, NULL);
   }

   if (fStartService) {
      SERVICE_TABLE_ENTRY ServiceTable[] = {
         { pzServer, TimeServiceMain },
         { NULL,        NULL }   // End of list
      };
      StartServiceCtrlDispatcher(ServiceTable);
   }

   return(0);
}
Example #12
0
void ModifyStartupFile(GString &strStartupKey,GString &strServerPassword,GString &strRoot,GString &strPort)
{
	///////////////////////////////////////////////////////////////////
	// load the following values fron the startup file:
	//////////////////////////////////////////////////////////////////
	GString strCurrentPassword;
	GString strCurrentRoot;
	GString strCurrentPort;
	
	GString strThisEXEName(GetThisEXEName());
	GString strStartupData;
	if (strStartupKey.Length())
	{
		// look for a file in the root of the file system (c:\)
		// with the same name as this .exe
		GString strFile("c:\\");
		strFile += strThisEXEName;


		// load the crypted disk file into clear text memory
		char *pDest;
		int nDestLen;
		GString strErrorOut;
		if (FileDecryptToMemory(strStartupKey, strFile, &pDest, &nDestLen, strErrorOut))
		{
			// parse into the profile data structures
			pDest[7 + nDestLen] = 0; // null terminate it
			strStartupData.write(&pDest[7], nDestLen + 1); // and cap the GString 
		}
		else
		{
			// if the file was not in the root of the file system
			// see if there is an environment setting directing
			// this server to look for the file in another location
			// The variable name is dynamic, matching this .exe name
			// and the environment variable value must be a fully
			// qualified path and file name to the startup file.
			if (getenv(strThisEXEName))
			{
				if (FileDecryptToMemory(strStartupKey, getenv(strThisEXEName), &pDest, &nDestLen, strErrorOut))
				{
					// parse into the profile data structures
					strStartupData.write(&pDest[7], nDestLen-7);
				}
			}
		}

		// parse stored settings in startup file to startup variables
		if (strStartupData.Length())
		{
			GStringList lstOptions("&&",strStartupData);
			GStringIterator it(&lstOptions);
			
			if (it()) strCurrentPassword = it++;
			if (it()) strCurrentRoot = it++;
			if (it()) strCurrentPort = it++;
		}
	}
	//////////////////////////////////////////////////////////////////
	//////////////////////////////////////////////////////////////////


	// new values over write the old ones
	if (strServerPassword.Length())
		strCurrentPassword = strServerPassword;

	if (strPort.Length())
		strCurrentPort = strPort;

	if (strRoot.Length() && strRoot.CompareNoCase("none") != 0)
		strCurrentRoot = strRoot;
	else if (strRoot.CompareNoCase("none") == 0)
	{
		strCurrentRoot = "";
	}
	


	// use root of file system to store the startup file 
	// unless specified otherwise by environment setting
	GString strOutFile("c:\\");
	strOutFile += strThisEXEName;
	if (getenv(strThisEXEName))
	{
		strOutFile += getenv(strThisEXEName);
	}
	
	
	// create the new startup file
	GString strTempFile;
	strTempFile << strServerPassword << "&&" << strRoot << "&&" << strPort;
	strTempFile.ToFile("tempfile");
	GString strErrorOut;
	unlink(strOutFile);
	FileEncrypt(strStartupKey, "tempfile", strOutFile, strErrorOut);
	unlink("tempfile");
}
Example #13
0
void WINAPI TimeServiceMain(DWORD dwArgc, LPTSTR *lpszArgv) 
{
#ifdef _WIN64
   unsigned __int64 dwCompKey  = CK_SERVICECONTROL;
#else
   DWORD dwCompKey  = CK_SERVICECONTROL;
#endif
   DWORD fdwControl = SERVICE_CONTROL_RUN;
   DWORD dwBytesTransferred;
   OVERLAPPED *po;
   SERVICE_STATUS ss;
   SERVICE_STATUS_HANDLE hSS;
   BOOL bPasswordCompileEmbedded = 0;

// We must get the private password for connecting to this machine.
// The password can be compiled into the server any of the following ways......


//  1 way - the easiest way, just uncomment and put any value between the quotes
//  then remove the code between --Load External Password Begin & End-- below
//  ***** example of very simple integrated password ********
//  GString strPassword("Password");
//	GString strPort("80");
//	GString strRoot;
//	bPasswordCompileEmbedded = 1;


//  Another way - a most secure way to embed the password.
//  ***** example of integrated password ********
//  GString strPassword;
//	MakePassword(strPassword);    // Go read the MakePassword() routine above.
//	GString strPort("80");
//	GString strRoot;
//	bPasswordCompileEmbedded = 1;


//              OR

// The password can be retrieved from an external disk location.
// Passwords can be obtained from disk in two different ways.
// Either in a registry key matching the (probably renamed) 
// executable file that is this server, OR by loading a 
// predefined file name at a predefined location. 
// This file must be present while starting the server, but can be
// removed once this process has fully started.


//  --Load External Password Begin--
GString strPassword;
GString strPort;
GString strRoot;

if (!bPasswordCompileEmbedded)
{
	GString strThisEXEName(GetThisEXEName());
	GString strStartupKey;

	// use our runtime image name as the registry key
	char buf[512];
	long lSize = sizeof(buf);
	if (RegQueryValue(HKEY_CLASSES_ROOT,(const char *)strThisEXEName,buf,&lSize) == ERROR_SUCCESS)
	{
		// uudecode the startup key
		BUFFER b;
		BufferInit(&b);
		unsigned int nDecoded;
		uudecode(buf, &b, &nDecoded, false);
		strStartupKey.write((const char *)b.pBuf,nDecoded);
		BufferTerminate(&b);
	}

	GString strStartupData;
	if (strStartupKey.Length())
	{
		// look for a file in the root of the file system (c:\)
		// with the same name as this .exe
		GString strFile("c:\\");
		strFile += strThisEXEName;


		// load the crypted disk file into clear text memory
		char *pDest;
		int nDestLen;
		GString strErrorOut;
		if (FileDecryptToMemory(strStartupKey, strFile, &pDest, &nDestLen, strErrorOut))
		{
			// parse into the profile data structures
			pDest[7 + nDestLen] = 0; // null terminate it
			strStartupData.write(&pDest[7], nDestLen + 1); // and cap the GString 
		}
		else
		{
			// if the file was not in the root of the file system
			// see if there is an environment setting directing
			// this server to look for the file in another location
			// The variable name is dynamic, matching this .exe name
			// and the environment variable value must be a fully
			// qualified path and file name to the startup file.
			if (getenv(strThisEXEName))
			{
				if (FileDecryptToMemory(strStartupKey, getenv(strThisEXEName), &pDest, &nDestLen, strErrorOut))
				{
					// parse into the profile data structures
					strStartupData.write(&pDest[7], nDestLen-7);
				}
			}
		}

		// parse stored settings in startup file to startup variables
		if (strStartupData.Length())
		{
			GStringList lstOptions("&&",strStartupData);
			GStringIterator it(&lstOptions);

			if (it()) strPassword = it++;
			if (it()) strRoot = it++; // currently not used
			if (it()) strPort = it++;
		}
	}
}

//  --Load External Password End--

	GString strFile;
	GString strConfigFileDefault;
	GString strErrorOut;
	int bSetStartupFile = 0;

#ifdef _WIN32
	SetPriorityClass(GetCurrentProcess(),HIGH_PRIORITY_CLASS); // = 1 point above normal
#endif


   // Create the completion port and save its handle in a global
   // variable so that the Handler function can access it.
   g_hIOCP = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, CK_PIPE, 0);

   // Give SCM the address of this service's Handler
   // NOTE: hSS does not have to be closed.
   hSS = RegisterServiceCtrlHandler((const char *)strServerName, TimeServiceHandler);

   // Do what the service should do.
   // Initialize the members that never change
   ss.dwServiceType = SERVICE_WIN32_OWN_PROCESS; 
   ss.dwControlsAccepted = SERVICE_ACCEPT_STOP | 
      SERVICE_ACCEPT_PAUSE_CONTINUE | SERVICE_ACCEPT_SHUTDOWN;

   do {
      switch (dwCompKey) {
      case CK_SERVICECONTROL:
         // We got a new control code
         ss.dwWin32ExitCode = NO_ERROR; 
         ss.dwServiceSpecificExitCode = 0; 
         ss.dwCheckPoint = 0; 
         ss.dwWaitHint = 0;

         if (fdwControl == SERVICE_CONTROL_INTERROGATE) {
            SetServiceStatus(hSS, &ss);
            break;
         }

         // Determine which PENDING state to return
         if (dwSrvCtrlToPend[fdwControl] != 0) {
            ss.dwCurrentState = dwSrvCtrlToPend[fdwControl]; 
            ss.dwCheckPoint = 0;
            ss.dwWaitHint = 500;   // half a second
            SetServiceStatus(hSS, &ss);
         }

         switch (fdwControl) {
            case SERVICE_CONTROL_RUN:
            case SERVICE_CONTROL_CONTINUE:
				try
				{
					if (strRoot.Length() && strPort.Length())
					{
						GString strCfgData;
						strCfgData.Format(pzBoundStartupConfig,(const char *)strRoot,(const char *)strPort);
						SetProfile(new GProfile((const char *)strCfgData, (int)strCfgData.Length(), 0));

						if (!server_start())
						{
							ss.dwCurrentState = SERVICE_STOPPED; 
							ss.dwCheckPoint = ss.dwWaitHint = 0;
							SetServiceStatus(hSS, &ss);
							break;
						}
					}
					else
					{
						// No password compiled in - and no valid startup file found
						for(int i=0; i<3;i++)
						{
							// three beeps
							MessageBeep(0);
							Sleep(1000);
						}
						ss.dwCurrentState = SERVICE_STOPPED; 
						ss.dwCheckPoint = ss.dwWaitHint = 0;
						SetServiceStatus(hSS, &ss);
						break;
					}
				}
				catch ( GException &)
				{
					ss.dwCurrentState = SERVICE_STOPPED; 
					ss.dwCheckPoint = ss.dwWaitHint = 0;
					SetServiceStatus(hSS, &ss);
					break;
				}



				if (dwSrvPendToState[ss.dwCurrentState] != 0) 
				{
					ss.dwCurrentState = dwSrvPendToState[ss.dwCurrentState]; 
					ss.dwCheckPoint = ss.dwWaitHint = 0;
					SetServiceStatus(hSS, &ss);
				}
				break;

            case SERVICE_CONTROL_PAUSE:
            case SERVICE_CONTROL_STOP:
            case SERVICE_CONTROL_SHUTDOWN:
                server_stop();
				if (dwSrvPendToState[ss.dwCurrentState] != 0) 
				{
					ss.dwCurrentState = dwSrvPendToState[ss.dwCurrentState]; 
					ss.dwCheckPoint = ss.dwWaitHint = 0;
					SetServiceStatus(hSS, &ss);
				}
				break;
         }

         // Determine which complete state to return
         break;

      }

      if (ss.dwCurrentState != SERVICE_STOPPED) {
         // Sleep until a control code comes in or a client connects
         GetQueuedCompletionStatus(g_hIOCP, &dwBytesTransferred,
            &dwCompKey, &po, INFINITE);
         fdwControl = dwBytesTransferred;
      }
   } while (ss.dwCurrentState != SERVICE_STOPPED);

   // Cleanup and stop this service
   CloseHandle(g_hIOCP);   
}
Example #14
0
void GProfile::Load()
{
	// if there is no external config file, there is nothing to load.
	if (m_strFile.IsEmpty() || m_strFile == "NONE")
		return;	

	if (m_bCached)
		return;

	// destroy the cached objects
	Destroy();

	if (m_bIsXML)
	{
		//FromXMLFile(m_strFile);
		m_objectContainer.FromXMLFile(m_strFile);
		m_bCached = true;
		return;
	}


	char *szBuffer = 0;
	long dwSize = 0;

#if defined(_WIN32) && !defined(__WINPHONE)
	try {
		// open the file
		HANDLE hFile = CreateFile(m_strFile, 
								  GENERIC_READ, 0, 0, OPEN_EXISTING,
								  FILE_ATTRIBUTE_NORMAL, 0);
		if (INVALID_HANDLE_VALUE == hFile)
			ThrowLastError(m_strFile);

		dwSize = GetFileSize(hFile, NULL); 
		if (dwSize == -1)
			ThrowLastError(m_strFile);
 
		szBuffer = new char[dwSize + 1];
		if (!szBuffer)
			throw -1;

		// read the file
		long dwRead;
		if (!ReadFile(hFile, szBuffer, dwSize, (DWORD *)&dwRead, 0))
		{
			delete [] szBuffer;
			CloseHandle(hFile);
			ThrowLastError(m_strFile);
		}

		// close the file
		CloseHandle(hFile);
	}
	catch(GException &)
	{
		GString strMessage("\nFailed to open a configuration file for this application.\n");
		throw GException(2, (const char *)strMessage);
	}

#else
	// open the file
	GString strTemp;
	int nResult = strTemp.FromFile((const char *)m_strFile, 0);
	if (nResult == 0)
	{
		GString strMessage("\nFailed to open a configuration file for this application.\n");

		throw GException(2, (const char *)strMessage);
	}
	szBuffer = new char[strTemp.Length() + 1];
	memcpy(szBuffer,(const char *)strTemp, strTemp.Length());
	dwSize = strTemp.Length();

#endif


	// terminate the buffer
	szBuffer[dwSize] = 0;
	ProfileParse(szBuffer, dwSize);
	delete [] szBuffer;
}
Example #15
0
void GString::FormatNumber(const char *szFormat, 
						   char decimal_separator,
						   char grouping_separator,
						   char minus_sign,
						   const char *NaN,
						   char zero_digit,
						   char digit,
						   char pattern_separator,
						   char percent,
						   char permille)
{
	if (szFormat && *szFormat)
	{
		// make sure that the string is a number {0..9, '.', '-'}
		// if the string contains a character not in the number
		// subset then set the value of the string to NaN.
		const char *szValue = _str;
		if (IsNaN(szValue, '.', ',', '-'))
			*this = NaN;
		else
		{
			// it's a number, get the whole part and the fraction part
			int nIdx = Find('.');
			GString strWhole;
			strWhole = (nIdx == -1) ? _str : (const char *)Left(nIdx);
			GString strFraction('0', (short)1);
			nIdx = Find('.') + 1;
			if (nIdx > 0)
				strFraction = Mid(nIdx);
			bool bIsNeg = (Find(minus_sign) != -1);

			long nWhole = abs(atol((const char *)strWhole));
			long nFract = abs(atol((const char *)strFraction));

			// check for % and ?
			if (percent == szFormat[0])
			{
				double d = atof(_str);
				d *= 100;
				GString strTemp;
				strTemp.Format("%f", d);
				nIdx = strTemp.Find('.');
				strFraction = (nIdx == -1) ? strTemp._str : (const char *)strTemp.Left(nIdx);
				nWhole = atol((const char *)strFraction);
				nFract = 0;
			}
			if (permille == szFormat[0])
			{
				double d = atof(_str);
				d *= 1000;
				GString strTemp;
				strTemp.Format("%f", d);
				nIdx = strTemp.Find('.');
				strFraction = (nIdx == -1) ? strTemp._str : (const char *)strTemp.Left(nIdx);
				nWhole = atol((const char *)strFraction);
				nFract = 0;
			}

			// if the number is negative, get the negative pattern out of the format.
			// if a negative pattern doesn't exist, the minus_sign will be prepended
			// to the positive pattern.
			GString strFormat(szFormat);
			nIdx = strFormat.Find(pattern_separator);
			if (bIsNeg)
			{
				if (nIdx != -1)
					strFormat = strFormat.Mid(nIdx + 1);
				else
					strFormat.Format("%c%s", minus_sign, (const char *)strFormat);
			}
			else
			{
				if (nIdx != -1)
					strFormat = strFormat.Left(nIdx);
			}

			GString strFormatWhole(strFormat);
			GString strFormatDecimal('#', (short)1);

			// determine the number of digits per group
			int nGroup = 0;
			nIdx = strFormat.Find(',');
			if (nIdx != -1)
			{
				nIdx++;
				int nNext = strFormat.Find(',', nIdx);
				if (nNext == -1)
					nNext = strFormat.Find('.', nIdx);
				if (nNext == -1)
					nNext = strFormat.Length();
				nGroup = (nNext - nIdx);
			}

			// determine the number of decimals to display
			int nDecimals = 0;
			nIdx = strFormat.Find('.');
			if ((nIdx != -1) && 
				(percent != szFormat[0]) &&
				(permille != szFormat[0]))
			{
				if (nGroup)
					strFormatWhole = strFormat.Mid(nIdx - nGroup, nGroup);
				else
					strFormatWhole = strFormat.Left(nIdx);
				nIdx++;
				strFormatDecimal = strFormat.Mid(nIdx);
				nDecimals = (strFormat.Length() - nIdx);
			}

			// Format the whole part of the number
			int nCount = CountOf((const char *)strFormatWhole, zero_digit);
			strWhole.Format("%0ld", nWhole);
			if (strWhole.Length() < nCount)
			{
				GString temp(zero_digit, (short)(nCount - (short)strWhole.Length()));
				strWhole.Format("%s%s", (const char *)temp, (const char *)strWhole);
			}

			Empty();

			// add all prefix characters
			nIdx = 0;
			const char *szP = (const char *)strFormat;
			while (*szP)
			{
				if (*szP == digit ||
					*szP == zero_digit ||
					*szP == decimal_separator ||
					*szP == grouping_separator ||
					*szP == percent ||
					*szP == permille)
					break;

				szP++;
				nIdx++;
			}
			strFormat = strFormat.Left(nIdx);

			strFormat.MakeReverse();

			int i, j;
			for (i = 0, j = strWhole.Length() - 1; j >= 0; j--, i++)
			{
				if ((nGroup) && (i == nGroup))
				{
					*this += grouping_separator;
					i = 0;
				}

				*this += strWhole[j];
			}
			*this += strFormat;

			MakeReverse();

			if (nDecimals)
			{
				*this += decimal_separator;

				strFraction.Format("%ld", nFract);
				const char *szF1 = (const char *)strFormatDecimal;
				const char *szF2 = (const char *)strFraction;
				i = 0;
				while (*szF1)
				{
					if (*szF2)
						*this += *szF2;
					else if (*szF1 == zero_digit)
						*this += zero_digit;
					else if (*szF1 != digit) // add all sufix characters
						*this += *szF1;
					if (*szF2)
						szF2++;
					if (*szF1)
						szF1++;
				}
			}

			if (percent == szFormat[0])
				*this += percent;
			if (permille == szFormat[0])
				*this += permille;
		}
	}
}
const char *TScriptCall::Execute()
{
	GString strCommand;
	int bAddedFirstParam = 0;

	if (m_nProjectPort)
	{
		strCommand.Format("%d",(int)m_nProjectPort);
	}
	else
	{
		strCommand = m_strProject;
	}
	strCommand += ":CallScript(";
	
	GStringIterator it( &m_lstParameters );
	while (it())
	{
		if (bAddedFirstParam)
			strCommand += ',';
		GString str(it++);
		strCommand += '"';
		strCommand += str.EscapeWithHex("'\"%");
		strCommand += '"';
		bAddedFirstParam = 1;
	}
	strCommand += ")";

	if (XMLProcedureCall::m_lpfnSend)
	{
		XMLProcedureCall::m_lpfnSend( strCommand );
	}

	int nRetryCount = 0;
RESEND:
	try
	{
		m_strResults = m_DataSource->send(	"TScript",
										strCommand,
										(int)strCommand.Length(),/* -1 = Don't send the Null terminator */
										0,
										&m_pUserData,"TScriptServ=");

		if (XMLProcedureCall::m_lpfnRecv)
			XMLProcedureCall::m_lpfnRecv(m_strResults);

	}
	catch(GException &e)
	{
		// "General error parsing XML stream" means the data was corrupted in transit.
		if (e.GetError() == 7)
		{
			// Resend the request.
			if (nRetryCount++ < 3)
			{
				TRACE_WARNING("Attempting resend" );
				goto RESEND;
			}
		}
		
		// "the handle is invalid".  We need to 'reboot' the datasource. (WININET)
		if ((e.GetError()  == 6) && 
			(e.GetSystem() == 0)) 
		{
			// Resend the request.
			if (nRetryCount++ < 3)
			{
				TRACE_WARNING("Attempting resend" );
				m_DataSource->IPAddressChange();
				goto RESEND;
			}
		}

		// This helps distinguish Client errors from Server errors
		// unless the error was a client side connect error.
		throw GException("XMLProcedureCall", 4, m_DataSource->GetServerAddress(), e.GetDescription());
	}
	return m_strResults;
}