summaryrefslogtreecommitdiffstats
path: root/source/cHeartBeat.cpp
blob: b518a753a6df2db9a6e8c3630157940d7b56596e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
#include "cHeartBeat.h"
#include "cMCLogger.h"
#include "md5/md5.h"

#include <stdio.h>

#include "cRoot.h"
#include "cServer.h"
#include "cSleep.h"

cHeartBeat::cHeartBeat()
{
	m_State = 0;
	Authenticate();
}

cHeartBeat::~cHeartBeat()
{
}

void cHeartBeat::ReceivedData( char a_Data[256], int a_Size )
{
	if( a_Size < 0 )	// Disconnected
		return;

	char MySalt[] = "1234567890";

	if( a_Size == 0 )
	{
		Authenticate();
		return;
	}

	bool bLoop = false;
	do
	{
		switch (m_State)
		{
		case 1:
			{
				m_ServerID = std::string( a_Data, a_Size );
				LOGINFO("Got server ID %s", m_ServerID.c_str() );
				std::string Hash = md5( m_ServerID + std::string( MySalt ) );
				CloseSocket();
				if( Connect( "mc-server.org", 80 ) )
				{
					SendMessage( (std::string("GET http://master.mc-server.org/?hash=") + Hash + std::string("&server=") + m_ServerID + "\n").c_str() );
					m_State = 2;
				}
			}
			break;
		case 2:
			{
				std::string ReturnedString = std::string( a_Data, a_Size );
				if( ReturnedString.compare("VALIDATED") == 0 )
				{
					LOGINFO("Successfully validated server on master server list");
				}
				else
				{
					LOGINFO("Could not validate server! Will try again later.");
					cSleep::MilliSleep( 10*1000 );
					Authenticate();
					return;
				}
				m_State = 3;
			}	// Don't break, but fall through and update server info
		case 3:
			{
				cSleep::MilliSleep( 10*1000 );
				SendUpdate();
				m_State = 4;
			}
			break;
		case 4:
			{
				if( a_Data[0] == '0' )
				{
					LOGINFO("Successfully updated server info!");
					cSleep::MilliSleep( 10*1000 );
					SendUpdate();
				}
				else
				{
					LOGINFO("Failed to update server info, reauthenticating");
					Authenticate();
				}
			}
		default:
			break;
		};
	} while( bLoop );
}

void cHeartBeat::SendUpdate()
{
	CloseSocket();
	if( Connect( "mc-server.org", 80 ) )
	{
		int Port = cRoot::Get()->GetServer()->GetPort();
		char c_Port[16];
		sprintf_s( c_Port, 16, "%i", Port );

		std::string sPort = std::string( c_Port );
		std::string sChecksum = md5( m_ServerID + sPort );
		SendMessage( (std::string("GET http://master.mc-server.org/?update=") + m_ServerID + std::string("&checksum=") + sChecksum + std::string("&port=") + sPort + "\n").c_str() );
	}
}

void cHeartBeat::Authenticate()
{
	CloseSocket();
	if( Connect( "mc-server.org", 80 ) )
	{
		m_State = 1;
		int RetVal = SendMessage( "GET http://master.mc-server.org/\r\n\r\n");
		LOGINFO("Returned %i", RetVal );
	}
}