This is the complete file and not complete application.
#include "Listener.h"
#include "Parser.h"
using namespace System::Configuration;
using namespace System;
using namespace System::IO;
using namespace System::Net;
using namespace System::Net::Sockets;
using namespace System::Threading;
using namespace ENS;
using namespace ENSAssembly;
Listener::Listener(void)
{
log = LoggerPool::getInstance()->getLog(LOG_TYPE::LISTENER);
if(log == nullptr){
throw gcnew IOException("Failed to create listener log");
}
IPAddress^ localAddr;
String ^tport = System::Configuration::ConfigurationManager::AppSettings["port"];
if(String::IsNullOrEmpty(tport)){
tport = "6550";
}
port = System::Convert::ToInt32(tport);
log->logInfo("Port: " + port);
localip = System::Configuration::ConfigurationManager::AppSettings["serverIp"];
if(String::IsNullOrEmpty(localip) || (localip->Equals("localhost"))){
localAddr = IPAddress::Parse( "127.0.0.1" );
}else{
localAddr = IPAddress::Parse(localip);
}
//create the server
log->logInfo("listening on: " + localAddr);
server = gcnew TcpListener(localAddr, port);
//check the last time the application started. Will be used to determine if a page is needed.
#if DEBUG
string applicationName =
Environment.GetCommandLineArgs()[0];
#else
String^ applicationName =
Environment::GetCommandLineArgs()[0];
#endif
String^ exePath = System::IO::Path::Combine(
Environment::CurrentDirectory, applicationName);
System::Configuration::Configuration^ config = System::Configuration::ConfigurationManager::OpenExeConfiguration(exePath);
lastStart = config->AppSettings->Settings["lastStart"]->Value;
String^ nowTicks = DateTime::Now.Ticks + "";
config->AppSettings->Settings["lastStart"]->Value = nowTicks;
config->Save(ConfigurationSaveMode::Modified);
}
Listener::~Listener(void){
if(server != nullptr)
server->Stop();
}
void Listener::waitForMessage(){
array<Byte> ^buffer = gcnew array<Byte>(1024);
String ^data = nullptr;
Int32 len;
Parser^ parser = Parser::getInstance();
long long elapsed, nowtime, prevtime, delayTime;
DateTime now = DateTime::Now;
bool isPrimary;
String ^failcode = "RESTART";
String^ type = System::Configuration::ConfigurationManager::AppSettings["serverType"];
if (!String::IsNullOrEmpty(type) && type->Equals("PRIMARY")){
isPrimary = true;
}
else{
isPrimary = false;
}
log->logInfo("Starting Listener Server");
server->Start();
//Send startup message
String ^iid = System::Configuration::ConfigurationManager::AppSettings["instanceId"];
// String^ iid = "777";
if (String::IsNullOrEmpty(iid)){
iid = "777";
}
if (isPrimary){
//check last start time. We only want to page if this is the primary server. Backup can just email.
if (lastStart != nullptr){
nowtime = now.Ticks;
prevtime = Int64::Parse(lastStart);
if (prevtime == 0){
prevtime = nowtime;
}
// A single tick represents one hundred nanoseconds or one ten-millionth of a second.
// There are 10,000 ticks in a millisecond, or 10 million ticks in a second.
elapsed = nowtime - prevtime;
}
else{
elapsed = 0;
}
delayTime = (MIN_TO_PAGE * 60 * 10000000);
//has it restarted in the last XX minutes?
if (elapsed < delayTime){ //convert to ticks, see calc above
//want to send page.
failcode = "PAGE";
log->logInfo("Recently restarted, triggering page. Elapsed time: " + elapsed + " DelayTime: " + delayTime);
}
else{
log->logInfo("Restarted, not triggering page. Elapsed time: " + elapsed + " DelayTime: " + delayTime);
}
}
log->logInfo("Last Start: " + lastStart + " Now: " + nowtime);
String^ timestring = now.ToString("yyyy-MM-dd HH.mm.ss");
parser->processMessage("ESPWTO5I 11111 TEST " + timestring + " ENSSTART ENSPROD 11111 ENS#PROD 1 EXEC " + failcode + " " + iid + " ENS2 $IPS ESP(V826772) " + localip);
while(true){
try{
if(server->Pending())
{
TcpClient^ client = server->AcceptTcpClient();
data = nullptr;
NetworkStream^ stream = client->GetStream();
do{
try{
if (!client->Connected){
client->Close();
}
do
{
len = stream->Read(buffer, 0, buffer->Length);
data = String::Concat(data, Text::Encoding::ASCII->GetString(buffer, 0, len));
} while (stream->DataAvailable);
//len = stream->Read(buffer, 0, buffer->Length);
//data = String::Concat(data, Text::Encoding::ASCII->GetString(buffer, 0, len));
if (data->Length >= 8){
//check if this is a real request
if (!data->StartsWith("ESPWTO") && !data->StartsWith("CA7SMF3") && !data->StartsWith("ENSTEST")
&& !data->StartsWith("MARAEMER") && !data->StartsWith("SNOW_CREATE")){
//break the connection, probably a improper scan.
client->Close();
log->logInfo("Discarding message, threw global exception. Data is: " + data);
data = "BADDATA";
break;
}
}
}catch(...){
//blow this joint!
client->Close();
log->logInfo("Discarding message, threw global exception. Data is: " + data);
data = "BADDATA";
break;
}
}while ( stream->DataAvailable );
data = data->Trim();
log->logInfo("Listener received: " + data);
if(data->StartsWith("ESPWTO5I") || data->StartsWith("ESPWTO6I") || data->StartsWith("CA7SMF3")
|| data->StartsWith("ENSTEST") || data->StartsWith("MARAEMER") || data->StartsWith("SNOW_CREATE")){
array<Byte>^ack = Text::Encoding::ASCII->GetBytes( "ACK");
stream->Write(ack, 0, 3);
String ^ip = (((IPEndPoint^)(client->Client->RemoteEndPoint))->Address)->ToString();
client->Close();
if (data->StartsWith("CA7SMF3")){
data = data + " NOREPLY";
} else if (!data->StartsWith("MARAEMER")){
data = data + " " + ip;
}
parser->processMessage(data);
}else{
//ignore GET & HELP request from port scan.
log->logInfo("Discarding message (doesn't start with ESPWTO5I or ESPWTO6I): " + data);
client->Close();
}
log->logInfo("-----------------------------------------------");
}else{
if(shutdown){
log->logInfo("Listener exiting.");
server->Stop();
log->Close();
delete log;
delete server;
log = nullptr;
server = nullptr;
return;
}else{
Thread::Sleep(PENDING_SLEEP_TIME);
}
}
}catch(SocketException^ e){
log->logInfo("Error: " + e->ErrorCode + " " + e->Message);
}catch(IOException^ ioe){
log->logError(gcnew String(__FUNCTION__), "Error: " + ioe->Message, ioe);
}
}
}