Initial commit (2011)

This commit is contained in:
Melissa 2020-04-28 16:14:34 +02:00
commit 4fab4f9d86
8 changed files with 1220 additions and 0 deletions

2
.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
bin/
*.pidb

34
gServer.sln Normal file
View File

@ -0,0 +1,34 @@

Microsoft Visual Studio Solution File, Format Version 10.00
# Visual Studio 2008
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "gServer", "gServer\gServer.csproj", "{6F404B72-8B0D-4A82-BD61-5A5168EF8724}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x86 = Debug|x86
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{6F404B72-8B0D-4A82-BD61-5A5168EF8724}.Debug|x86.ActiveCfg = Debug|x86
{6F404B72-8B0D-4A82-BD61-5A5168EF8724}.Debug|x86.Build.0 = Debug|x86
{6F404B72-8B0D-4A82-BD61-5A5168EF8724}.Release|x86.ActiveCfg = Release|x86
{6F404B72-8B0D-4A82-BD61-5A5168EF8724}.Release|x86.Build.0 = Release|x86
EndGlobalSection
GlobalSection(MonoDevelopProperties) = preSolution
StartupItem = gServer\gServer.csproj
Policies = $0
$0.TextStylePolicy = $1
$1.inheritsSet = null
$1.scope = text/x-csharp
$0.CSharpFormattingPolicy = $2
$2.StatementBraceStyle = NextLine
$2.PlaceElseOnNewLine = True
$2.PlaceElseIfOnNewLine = True
$2.PlaceCatchOnNewLine = True
$2.PlaceFinallyOnNewLine = True
$2.PlaceWhileOnNewLine = True
$2.inheritsSet = Mono
$2.inheritsScope = text/x-csharp
$2.scope = text/x-csharp
EndGlobalSection
EndGlobal

14
gServer.userprefs Normal file
View File

@ -0,0 +1,14 @@
<Properties>
<MonoDevelop.Ide.Workspace ActiveConfiguration="Debug|x86" />
<MonoDevelop.Ide.Workbench ActiveDocument="gServer\ServerlistServer.cs">
<Files>
<File FileName="gServer\Main.cs" Line="110" Column="60" />
<File FileName="gServer\ServerlistServer.cs" Line="106" Column="3" />
<File FileName="gServer\User.cs" Line="716" Column="3" />
</Files>
</MonoDevelop.Ide.Workbench>
<MonoDevelop.Ide.DebuggingService.Breakpoints>
<BreakpointStore />
</MonoDevelop.Ide.DebuggingService.Breakpoints>
<MonoDevelop.Ide.DebuggingService.PinnedWatches />
</Properties>

27
gServer/AssemblyInfo.cs Normal file
View File

@ -0,0 +1,27 @@
using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("gServer")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("1.0.*")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]

182
gServer/Main.cs Normal file
View File

@ -0,0 +1,182 @@
using System;
using System.Threading;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using MySql.Data.MySqlClient;
namespace gServer
{
public class MainClass
{
public int SecondsPassed = 0;
public int SecondsPassedHalf = 0;
private String MySQL_Host = "localhost";
private String MySQL_Username = "gs";
private String MySQL_Password = "gs";
private String MySQL_Database = "gs";
private String MySQL_Connector = "";
private IDbConnection MySQL_Connection;
public MrAG.Serverlist.Server Listener;
public MrAG.Serverlist.Server ListenerAlternative;
public MrAG.Serverlist.Server ServerlistListener;
public List<User> Users = new List<User>();
public List<ServerlistServer> ServerlistServers = new List<ServerlistServer>();
public List<ServerData> Servers = new List<ServerData>();
public void Start()
{
this.MySQL_Connector = "Server=" + this.MySQL_Host + ";" +
"Database=" + this.MySQL_Database + ";" +
"User ID=" + this.MySQL_Username + ";" +
"Password=" + this.MySQL_Password + ";" + "Pooling=false";
this.MySQL_Connection = new MySqlConnection(this.MySQL_Connector);
this.MySQL_Connection.Open();
this.Query("UPDATE `users` SET `API_Sessionkey`=''");
this.Listener = MrAG.Serverlist.Host("__site", 17000, "__site", false);
this.ListenerAlternative = MrAG.Serverlist.Host("__site", 2222, "__site", false);
this.Listener.OnIncomingConnection = new Action<MrAG.Networking.IncomingConnection>(IncomingConnection);
this.Listener.OnFinishedConnection = new Action<MrAG.Networking.IncomingConnection>(FinishedConnection);
this.ListenerAlternative.OnIncomingConnection = new Action<MrAG.Networking.IncomingConnection>(IncomingConnection);
this.ListenerAlternative.OnFinishedConnection = new Action<MrAG.Networking.IncomingConnection>(FinishedConnection);
this.Listener.Timeout = 2000;
this.ListenerAlternative.Timeout = 2000;
this.Log("GamerServices server started on port 17000 (and 2222).");
this.ServerlistListener = MrAG.Serverlist.Host("__site", 8443, "__site", false);
this.ServerlistListener.OnIncomingConnection = new Action<MrAG.Networking.IncomingConnection>(Serverlist_IncomingConnection);
this.ServerlistListener.OnFinishedConnection = new Action<MrAG.Networking.IncomingConnection>(Serverlist_FinishedConnection);
this.ServerlistListener.Timeout = 2000;
double LastKeepAliveForSQL = DateTime.Now.TimeOfDay.TotalMinutes; // keepalive :3
while(true)
{
if (Math.Abs(LastKeepAliveForSQL - DateTime.Now.TimeOfDay.TotalMinutes) >= 30){ // 30 min interval
this.Query("SELECT 1"); // Completly useless query, just for keepalive :3
LastKeepAliveForSQL = DateTime.Now.TimeOfDay.TotalMinutes;
}
this.Listener.Update();
this.ListenerAlternative.Update();
this.ServerlistListener.Update();
for(int i=0; i<this.Users.Count; i++)
this.Users[i].Update();
for(int i=0; i<this.ServerlistServers.Count; i++)
this.ServerlistServers[i].Update();
Thread.Sleep(17);
}
}
public void Log(String Text)
{
Console.WriteLine(String.Format("[{0}] {1}", DateTime.Now.ToString(), Text));
}
public long Epoch()
{
return (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000;
}
public void IncomingConnection(MrAG.Networking.IncomingConnection c)
{
}
public void FinishedConnection(MrAG.Networking.IncomingConnection c)
{
this.Log("Connection accepted from " + c.IP);
this.Users.Add(new User(c, this));
}
public void Serverlist_IncomingConnection(MrAG.Networking.IncomingConnection c)
{
}
public void Serverlist_FinishedConnection(MrAG.Networking.IncomingConnection c)
{
this.Log("Serverlist connection accepted from " + c.IP);
this.ServerlistServers.Add(new ServerlistServer(c, this));
}
public Hashtable[] Query(String qry)
{
IDbCommand dbcmd = this.MySQL_Connection.CreateCommand();
dbcmd.CommandText = qry;
IDataReader dr = null;
try{
dr = dbcmd.ExecuteReader();
}catch(Exception ex){
this.Log("********************************************\nQUERY ERROR:\n" + ex.Message + "\n\nQUERY WAS:\n" + qry + "\n********************************************");
}
return Rows(dr);
}
public Hashtable[] Rows(IDataReader resource)
{
List<Hashtable> ret = new List<Hashtable>();
while(resource.Read())
{
Hashtable newRow = new Hashtable();
for (int i=0; i<resource.FieldCount; i++)
newRow[resource.GetName(i)] = resource.GetValue(i).ToString();
ret.Add(newRow);
}
resource.Close();
resource.Dispose();
resource = null;
return ret.ToArray();
}
public int Intval(String input)
{
int val = 0;
int.TryParse(input, out val);
return val;
}
public String Safe(String input)
{
String ret = input;
ret = ret.Replace("\\", "\\\\"); // \ -> \\
ret = ret.Replace("'", "\\'"); // ' -> \'
return ret;
}
public string MD5(string input)
{
System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();
System.Text.StringBuilder s = new System.Text.StringBuilder();
byte[] bs = System.Text.Encoding.UTF8.GetBytes(input);
bs = x.ComputeHash(bs);
foreach (byte b in bs)
{
s.Append(b.ToString("x2"));
}
return s.ToString().ToLower();
}
public static void Main (string[] args)
{
new MainClass().Start();
}
}
}

151
gServer/ServerlistServer.cs Normal file
View File

@ -0,0 +1,151 @@
using System;
using System.Data;
using System.Collections;
using System.Collections.Generic;
using MySql.Data.MySqlClient;
namespace gServer
{
public class ServerData
{
public string Name = "null";
public string Meta = "null";
public string Game = "null";
public int CurrentUsers = 0;
public int MaxUsers = 0;
public string IP = "null";
public int Port = 0;
public long lastUpdate;
}
public class ServerlistServer
{
public MainClass main;
public MrAG.Networking.IncomingConnection Connection;
public ServerData serverData = new ServerData();
public ServerlistServer (MrAG.Networking.IncomingConnection c, MainClass main)
{
this.main = main;
c.Connection.Packets[0] = new Action<MrAG.Networking.Packet>(Packet_Add);
c.Connection.Packets[1] = new Action<MrAG.Networking.Packet>(Packet_Update);
c.Connection.Packets[2] = new Action<MrAG.Networking.Packet>(Packet_Offline);
c.Connection.Packets[3] = new Action<MrAG.Networking.Packet>(Packet_UpdatePlayerCount);
c.Connection.Packets[4] = new Action<MrAG.Networking.Packet>(Packet_UpdateMeta);
this.Connection = c;
}
public void Disconnected(bool Unexpected)
{
if(Unexpected)
this.main.Log(this.Connection.IP + " from Serverlist Server unexpectedly disconnected.");
this.main.Servers.Remove(this.serverData);
this.main.ServerlistServers.Remove(this);
}
public void Update()
{
try
{
this.Connection.Connection.Update();
}catch(Exception ex){
if(ex.Message == "The object was used after being disposed.")
{
this.Disconnected(true);
}
this.main.Log(this.Connection.IP + " from Serverlist Server errored: " + ex.Message);
this.Connection.Kick("Socket error");
}
}
public void InvalidPacket()
{
this.Connection.Kick("Invalid packet received!");
this.main.Log(this.Connection.IP + " from Serverlist Server kicked for an invalid packet.");
this.Disconnected(false);
}
public void Packet_Add(MrAG.Networking.Packet p)
{
bool shouldAdd = this.serverData.IP == "null";
this.serverData.IP = this.Connection.IP;
//this.serverData.IP = "127.0.0.1";
try
{
this.serverData.Name = p.ReadString();
this.serverData.Meta = p.ReadString();
this.serverData.Game = p.ReadString();
this.serverData.Port = p.ReadInt();
this.serverData.MaxUsers = p.ReadInt();
}catch{
this.InvalidPacket();
return;
}
if(shouldAdd)
{
this.main.Servers.Add(this.serverData);
this.main.Log("Added server " + this.serverData.Name + " to " + this.serverData.Game);
}else
this.main.Log("Tried adding " + this.serverData.Name + ", but shouldAdd = false");
p.Start_Send();
p.AddByte(0);
p.AddBool(shouldAdd);
if(!shouldAdd)
p.AddString("Already added!");
p.Finish_Send();
}
public void Packet_Update(MrAG.Networking.Packet p)
{
this.serverData.lastUpdate = this.main.Epoch();
if(this.serverData.IP == "null")
{
this.Connection.Connection.Connection.Start_Send();
this.Connection.Connection.Connection.AddByte(1);
this.Connection.Connection.Connection.AddBool(false);
this.Connection.Connection.Connection.Finish_Send();
}
}
public void Packet_Offline(MrAG.Networking.Packet p)
{
this.main.Servers.Remove(this.serverData);
this.serverData = new ServerData();
this.main.Log("Server " + this.Connection.IP + " stopped");
}
public void Packet_UpdatePlayerCount(MrAG.Networking.Packet p)
{
try
{
this.serverData.CurrentUsers = p.ReadInt();
}catch{
this.InvalidPacket();
return;
}
}
public void Packet_UpdateMeta(MrAG.Networking.Packet p)
{
try
{
this.serverData.Meta = p.ReadString();
}catch{
this.InvalidPacket();
return;
}
}
}
}

757
gServer/User.cs Normal file
View File

@ -0,0 +1,757 @@
using System;
using System.Data;
using System.Collections;
using System.Collections.Generic;
using MySql.Data.MySqlClient;
namespace gServer
{
public enum MessageboxIcon : byte { Asterisk, Error, Exclamation, Hand, Info, None, Question, Stop, Warning }
public class User
{
public MainClass main;
public MrAG.Networking.IncomingConnection Connection;
public int UserID = 0;
public String Username = "";
public String Sessionkey = "";
public String Avatar = "";
public int UpdateCount = 0;
public List<User> Friends = new List<User>();
public User(MrAG.Networking.IncomingConnection c, MainClass main)
{
this.main = main;
// 0-2: User related packets
c.Connection.Packets[0] = new Action<MrAG.Networking.Packet>(Packet_Login);
c.Connection.Packets[1] = new Action<MrAG.Networking.Packet>(Packet_Logout);
c.Connection.Packets[2] = new Action<MrAG.Networking.Packet>(Packet_Ping);
// 3-7: Friends related packets
c.Connection.Packets[3] = new Action<MrAG.Networking.Packet>(Packet_Friendslist);
c.Connection.Packets[5] = new Action<MrAG.Networking.Packet>(Packet_Chatmessage);
c.Connection.Packets[6] = new Action<MrAG.Networking.Packet>(Packet_FriendrequestConfirmation);
c.Connection.Packets[7] = new Action<MrAG.Networking.Packet>(Packet_Friendrequest);
// 10-29: Game related packets
c.Connection.Packets[10] = new Action<MrAG.Networking.Packet>(Packet_Gamelist);
c.Connection.Packets[11] = new Action<MrAG.Networking.Packet>(Packet_Updates);
c.Connection.Packets[12] = new Action<MrAG.Networking.Packet>(Packet_GameAchievements);
c.Connection.Packets[13] = new Action<MrAG.Networking.Packet>(Packet_GameLeaderboards);
c.Connection.Packets[14] = new Action<MrAG.Networking.Packet>(Packet_IngameChange);
c.Connection.Packets[15] = new Action<MrAG.Networking.Packet>(Packet_ServerList);
// 30-39: General
c.Connection.Packets[31] = new Action<MrAG.Networking.Packet>(Packet_AvatarRequest);
// 40-49: Statistics submissions
c.Connection.Packets[40] = new Action<MrAG.Networking.Packet>(Packet_Achievement_Add);
c.Connection.Packets[41] = new Action<MrAG.Networking.Packet>(Packet_Achievement_Set);
c.Connection.Packets[42] = new Action<MrAG.Networking.Packet>(Packet_Leaderboard_Submit);
this.Connection = c;
}
public Hashtable UserRow
{
get
{
return this.main.Query("SELECT * FROM `users` WHERE `ID`=" + this.UserID)[0];
}
}
public void Messagebox(String Title, String Text, MessageboxIcon Icon)
{
this.Connection.Connection.Connection.Start_Send();
this.Connection.Connection.Connection.AddByte(30);
this.Connection.Connection.Connection.AddString(Title);
this.Connection.Connection.Connection.AddString(Text);
this.Connection.Connection.Connection.AddByte((byte)Icon);
this.Connection.Connection.Connection.Finish_Send();
}
public void Disconnected(bool Unexpected)
{
if(Unexpected)
this.main.Log(this.Connection.IP + " (" + this.Username + ") unexpectedly disconnected.");
if(this.UserID != 0)
this.main.Query("UPDATE `users` SET `API_SessionKey`='' WHERE `ID`=" + this.UserID);
foreach (User Friend in this.Friends){
Friend.Connection.Connection.Connection.Start_Send();
Friend.Connection.Connection.Connection.AddByte(4);
Friend.Connection.Connection.Connection.AddInt(this.UserID);
Friend.Connection.Connection.Connection.AddBool(false);
Friend.Connection.Connection.Connection.Finish_Send();
Friend.Friends.Remove(this);
}
this.main.Users.Remove(this);
}
public void Update()
{
try
{
this.Connection.Connection.Update();
}catch(Exception ex){
if(ex.Message == "The object was used after being disposed.")
{
this.Disconnected(true);
}
this.main.Log(this.Connection.IP + " (" + this.Username + ") errored: " + ex.Message);
this.Connection.Kick("Socket error");
}
UpdateCount++;
if(UpdateCount >= 1000)
{
UpdateCount = 0;
try
{
this.Connection.Connection.Connection.Start_Send();
this.Connection.Connection.Connection.AddByte(2);
this.Connection.Connection.Connection.Finish_Send();
}catch{}
}
}
public void InvalidPacket()
{
this.Connection.Kick("Invalid packet received!");
this.main.Log(this.Connection.IP + " (" + this.Username + ") kicked for an invalid packet.");
this.Disconnected(false);
}
public void Packet_Login(MrAG.Networking.Packet p)
{
String Username;
String Password;
try
{
Username = p.ReadString();
Password = p.ReadString();
}catch{
this.InvalidPacket();
return;
}
Hashtable[] rows = this.main.Query("SELECT * FROM `users` WHERE `Username`='" + this.main.Safe(Username) + "' AND `Password`='" + this.main.Safe(Password) + "'");
if(rows.Length == 1)
{
this.UserID = int.Parse((String)rows[0]["ID"]);
this.Username = (String)rows[0]["Username"];
this.Sessionkey = this.main.MD5(DateTime.Now.TimeOfDay.TotalMilliseconds.ToString() + "GamerServices :D");
this.Avatar = this.main.MD5((String)rows[0]["Email"]);
this.main.Query("UPDATE `users` SET `API_SessionKey`='" + this.Sessionkey + "' WHERE `ID`=" + rows[0]["ID"]);
p.Start_Send();
p.AddByte(0);
p.AddBool(true);
p.AddString(this.Sessionkey);
p.Finish_Send();
Hashtable[] FriendConnections = this.main.Query("SELECT * FROM `friends` WHERE `User`=" + this.UserID + " OR `Friend`=" + this.UserID);
for(int i=0; i<FriendConnections.Length; i++)
{
int FriendID = int.Parse((String)FriendConnections[i]["Friend"]);
if(FriendID == this.UserID)
FriendID = int.Parse((String)FriendConnections[i]["User"]);
foreach(User User in this.main.Users)
{
if (User != this){
if (User.Username == Username){ //inb4 500 angelos
User.Disconnected(true);
}
if(User.UserID == FriendID)
{
User.Connection.Connection.Connection.Start_Send();
User.Connection.Connection.Connection.AddByte(4);
User.Connection.Connection.Connection.AddInt(this.UserID);
User.Connection.Connection.Connection.AddBool(true);
User.Connection.Connection.Connection.Finish_Send();
User.Friends.Add(this);
this.Friends.Add(User); // add him to the list, else we would need to loop much more then aculy needed!
}
}
}
}
this.main.Log(this.Connection.IP + " logged in as " + this.Username);
}else{
p.Start_Send();
p.AddByte(0);
p.AddBool(false);
p.Finish_Send();
this.main.Log(this.Connection.IP + " tried logging in with the wrong credentials for " + Username);
}
}
public void Packet_Logout(MrAG.Networking.Packet p)
{
this.main.Log(this.Connection.IP + " logged out from " + this.Username);
this.Disconnected(false);
}
public void Packet_Ping(MrAG.Networking.Packet p)
{
this.main.Query("UPDATE `users` SET `API_Time`=" + this.main.Epoch() + " WHERE `ID`=" + this.UserID.ToString());
}
public void Packet_Friendslist(MrAG.Networking.Packet p)
{
p.Start_Send();
p.AddByte(3);
Hashtable[] FriendConnections = this.main.Query("SELECT * FROM `friends` WHERE (`User`=" + this.UserID + " OR `Friend`=" + this.UserID + ") AND `Active`=1");
p.AddShort((short)FriendConnections.Length);
for(int i=0; i<FriendConnections.Length; i++)
{
int FriendID = int.Parse((String)FriendConnections[i]["Friend"]);
if(FriendID == this.UserID)
FriendID = int.Parse((String)FriendConnections[i]["User"]);
Hashtable Friend = this.main.Query("SELECT * FROM `users` WHERE `ID`=" + FriendID.ToString())[0];
p.AddString((String)Friend["Username"]);
p.AddInt(FriendID);
p.AddString(this.main.MD5((String)Friend["Email"]));
bool FriendOnline = (String)Friend["API_Sessionkey"] != "";
p.AddBool(FriendOnline);
if(FriendOnline)
{
p.AddShort(short.Parse((String)Friend["API_Playing"]));
}
}
p.Finish_Send();
Hashtable[] FriendRequests = this.main.Query("SELECT * FROM `friends` WHERE `Friend`=" + this.UserID + " AND `Active`=0");
for(int i=0; i<FriendRequests.Length; i++)
{
p.Start_Send();
p.AddByte(6);
Hashtable Friend = this.main.Query("SELECT * FROM `users` WHERE `ID`=" + FriendRequests[i]["User"])[0];
p.AddString((String)Friend["Username"]);
p.Finish_Send();
}
}
public void Packet_Chatmessage(MrAG.Networking.Packet p)
{
int FriendID = 0;
String Message = "";
try
{
FriendID = p.ReadInt();
Message = p.ReadString();
}catch{}
foreach(User User in this.Friends)
{
if(User.UserID == FriendID)
{
User.Connection.Connection.Connection.Start_Send();
User.Connection.Connection.Connection.AddByte(5);
User.Connection.Connection.Connection.AddInt(this.UserID);
User.Connection.Connection.Connection.AddString(Message);
User.Connection.Connection.Connection.Finish_Send();
break;
}
}
}
public void Packet_FriendrequestConfirmation(MrAG.Networking.Packet p)
{
String Name = "";
try
{
Name = p.ReadString();
}catch{}
Hashtable[] UserRes = this.main.Query("SELECT * FROM `users` WHERE `Username`='" + this.main.Safe(Name) + "'");
if(UserRes.Length == 1)
{
Hashtable User = UserRes[0];
bool Accept = p.ReadBool();
int userID = int.Parse((String)User["ID"]);
if(Accept){
this.main.Query("UPDATE `friends` SET `Active`=1 WHERE `User`=" + userID + " AND `Friend`=" + this.UserID + " AND `Active`=0");
foreach(User user in this.main.Users)
{
if(user.UserID == userID)
{
user.Connection.Connection.Connection.Start_Send();
user.Connection.Connection.Connection.AddByte(7);
user.Connection.Connection.Connection.AddString(this.Username);
user.Connection.Connection.Connection.AddInt(this.UserID);
user.Connection.Connection.Connection.AddString(this.Avatar);
user.Connection.Connection.Connection.AddBool(true);
user.Connection.Connection.Connection.Finish_Send();
user.Friends.Add(this); // add him to the list, else we would need to loop much more then aculy needed!
this.Friends.Add(user); // add him to the list, else we would need to loop much more then aculy needed!
break;
}
}
this.Connection.Connection.Connection.Start_Send();
this.Connection.Connection.Connection.AddByte(7);
this.Connection.Connection.Connection.AddString(this.Username);
this.Connection.Connection.Connection.AddInt(this.UserID);
this.Connection.Connection.Connection.AddString(this.main.MD5((String)User["Email"]));
this.Connection.Connection.Connection.AddBool((String)User["API_Sessionkey"] != "");
this.Connection.Connection.Connection.Finish_Send();
}else
this.main.Query("DELETE FROM `friends` WHERE `User`=" + int.Parse((String)User["ID"]) + " AND `Friend`=" + this.UserID + " AND `Active`=0");
}
}
public void Packet_Friendrequest(MrAG.Networking.Packet p)
{
String Name = "";
try
{
Name = p.ReadString();
}catch{}
Hashtable[] UserRes = this.main.Query("SELECT * FROM `users` WHERE `Username`='" + this.main.Safe(Name) + "'");
if(UserRes.Length == 1)
{
Hashtable User = UserRes[0];
int userid = int.Parse((String)User["ID"]);
this.main.Query("INSERT INTO `friends` (`User`,`Friend`,`Active`) VALUES(" + this.UserID + "," + int.Parse((String)User["ID"]) + ",0)");
bool FriendOnline = (String)User["API_Sessionkey"] != "";
if (FriendOnline){
p.Start_Send();
p.AddByte(6);
p.AddString(Name);
p.Finish_Send();
foreach(User user in this.main.Users)
{
if(user.UserID == userid)
{
user.Connection.Connection.Connection.Start_Send();
user.Connection.Connection.Connection.AddByte(6);
user.Connection.Connection.Connection.AddString(this.Username);
user.Connection.Connection.Connection.Finish_Send();
break;
}
}
}
}else{
this.Messagebox("Friend request", "The user '" + Name + "' is unknown!", MessageboxIcon.Exclamation);
}
}
public void Packet_Gamelist(MrAG.Networking.Packet p)
{
p.Start_Send();
p.AddByte(10);
Hashtable[] Rows = this.main.Query("SELECT * FROM `games` ORDER BY `Name` ASC");
Hashtable[] DeveloperRes = this.main.Query("SELECT * FROM `developers` WHERE `User`=" + this.UserID);
int gamestosend = 0;
bool isadmin = int.Parse((String)this.UserRow["Admin"]) == 1;
byte[] accesslist = null;
if (!isadmin){ // Dont create it if we are an admin, useless memory useage, besides why would we check if we already are a god damn admin?
accesslist = new byte[Rows.Length + 1]; // create acces table, 0 is invis, 1 is visble, 2 is dev, 3 is admin
for(int j=0; j<DeveloperRes.Length; j++) // loop truw the users dev games and set em to 2, less loops later on
accesslist[int.Parse((String)DeveloperRes[j]["Game"])] = 2;
for(int i=0; i<Rows.Length; i++)
{
short gameID = short.Parse((String)Rows[i]["ID"]);
// if its still invis after the dev check, check for visible to public
accesslist[gameID] = accesslist[gameID] == 0 ? byte.Parse((String)Rows[i]["Visible"]) : accesslist[gameID];
gamestosend += accesslist[gameID] > 0 ? 1 : 0;
}
}else // fuck looperdieloops, we are strong like freaking chuck noris!
gamestosend = Rows.Length;
p.AddInt(gamestosend);
for(int i=0; i<Rows.Length; i++)
{
short gameID = short.Parse((String)Rows[i]["ID"]);
if (isadmin || accesslist[gameID] > 0)
{
p.AddString((String)Rows[i]["Identifier"]);
p.AddString((String)Rows[i]["Name"]);
p.AddShort(gameID);
p.AddString((String)Rows[i]["Description"]);
p.AddString((String)Rows[i]["Executable"]);
p.AddBool(isadmin || accesslist[gameID] > 1);
}
}
p.Finish_Send();
}
public void Packet_Updates(MrAG.Networking.Packet p)
{
int AppID = 0;
try
{
AppID = (int)p.ReadShort();
}catch{
this.InvalidPacket();
return;
}
p.Start_Send();
p.AddByte(11);
p.AddString("1.0.0"); //TODO: Change.
p.AddShort((short)AppID);
p.Finish_Send();
}
public void Packet_GameAchievements(MrAG.Networking.Packet p)
{
short AppID = 0;
try
{
AppID = (short)p.ReadShort();
}catch{
this.InvalidPacket();
return;
}
p.Start_Send();
p.AddByte(12);
p.AddShort(AppID);
Hashtable[] Rows = this.main.Query("SELECT * FROM `achievements` WHERE `Game`=" + AppID.ToString());
p.AddInt(Rows.Length);
for(int i=0; i<Rows.Length; i++)
{
p.AddInt(int.Parse((String)Rows[i]["ID"]));
p.AddString((String)Rows[i]["Name"]);
p.AddString((String)Rows[i]["Description"]);
p.AddShort(short.Parse((String)Rows[i]["Points"]));
Hashtable[] EntryRes = this.main.Query("SELECT * FROM `achievements_entries` WHERE `User`=" + this.UserID.ToString() + " AND `Achievement`=" + (String)Rows[i]["ID"]);
if(EntryRes.Length == 0)
{
p.AddInt(0);
}
else
{
Hashtable Entry = EntryRes[0];
p.AddInt(int.Parse((String)Entry["Progress"]));
}
p.AddInt(int.Parse((String)Rows[i]["Progress"]));
}
p.Finish_Send();
}
public void Packet_GameLeaderboards(MrAG.Networking.Packet p)
{
short AppID = 0;
try
{
AppID = (short)p.ReadShort();
}catch{
this.InvalidPacket();
return;
}
p.Start_Send();
p.AddByte(13);
p.AddShort(AppID);
Hashtable[] Rows = this.main.Query("SELECT * FROM `leaderboards` WHERE `Game`=" + AppID.ToString());
p.AddInt(Rows.Length);
for(int i=0; i<Rows.Length; i++)
{
p.AddInt(int.Parse((String)Rows[i]["ID"]));
p.AddString((String)Rows[i]["Name"]);
p.AddString((String)Rows[i]["Description"]);
p.AddString((String)Rows[i]["Identifier"]);
}
p.Finish_Send();
}
public void Packet_Achievement_Add(MrAG.Networking.Packet p)
{
int AchievementID = 0;
int Amount = 0;
try
{
AchievementID = p.ReadInt();
Amount = p.ReadInt();
}catch{
this.InvalidPacket();
return;
}
if(this.UserID == 0)
{
this.Messagebox("Error", "Not logged in!", MessageboxIcon.Error);
return;
}
Hashtable[] AchievementRes = this.main.Query("SELECT * FROM `achievements` WHERE `ID`=" + AchievementID);
if(AchievementRes.Length != 1)
{
this.Messagebox("Error", "No such achievement!", MessageboxIcon.Error);
return;
}
Hashtable Achievement = AchievementRes[0];
Hashtable[] EntryRes = this.main.Query("SELECT * FROM `achievements_entries` WHERE `User`=" + this.UserID + " AND `Achievement`=" + (String)Achievement["ID"]);
if(EntryRes.Length == 1)
this.main.Query("UPDATE `achievements_entries` SET `Progress`=`Progress`+" + Amount + " WHERE `ID`=" + (String)EntryRes[0]["ID"]);
else
this.main.Query("INSERT INTO `achievements_entries` (`User`,`Achievement`,`Progress`) VALUES(" + this.UserID + "," + (String)Achievement["ID"] + "," + Amount + ")");
}
public void Packet_Achievement_Set(MrAG.Networking.Packet p)
{
int AchievementID = 0;
int Amount = 0;
try
{
AchievementID = p.ReadInt();
Amount = p.ReadInt();
}catch{
this.InvalidPacket();
return;
}
if(this.UserID == 0)
{
this.Messagebox("Error", "Not logged in!", MessageboxIcon.Error);
return;
}
Hashtable[] AchievementRes = this.main.Query("SELECT * FROM `achievements` WHERE `ID`=" + AchievementID);
if(AchievementRes.Length != 1)
{
this.Messagebox("Error", "No such achievement!", MessageboxIcon.Error);
return;
}
Hashtable Achievement = AchievementRes[0];
Hashtable[] EntryRes = this.main.Query("SELECT * FROM `achievements_entries` WHERE `User`=" + this.UserID + " AND `Achievement`=" + (String)Achievement["ID"]);
if(EntryRes.Length == 1)
this.main.Query("UPDATE `achievements_entries` SET `Progress`=" + Amount + " WHERE `ID`=" + (String)EntryRes[0]["ID"]);
else
this.main.Query("INSERT INTO `achievements_entries` (`User`,`Achievement`,`Progress`) VALUES(" + this.UserID + "," + (String)Achievement["ID"] + "," + Amount + ")");
}
public void Packet_Leaderboard_Submit(MrAG.Networking.Packet p)
{
int LeaderboardID = 0;
int Score = 0;
try
{
LeaderboardID = p.ReadInt();
Score = p.ReadInt();
}catch{
this.InvalidPacket();
return;
}
Hashtable[] LeaderboardRes = this.main.Query("SELECT * FROM `leaderboards` WHERE `ID`=" + LeaderboardID);
if(LeaderboardRes.Length == 0)
{
this.Messagebox("Error", "Unknown leaderboard!", MessageboxIcon.Error);
return;
}
Hashtable Leaderboard = LeaderboardRes[0];
Hashtable[] EntryRes = this.main.Query("SELECT * FROM `leaderboards_entries` WHERE `Leaderboard`=" + (String)Leaderboard["ID"] + " AND `User`=" + this.UserID + " ORDER BY `Score` DESC");
if(EntryRes.Length == 0)
{
// No entry yet, make a new one
this.main.Query("INSERT INTO `leaderboards_entries` (`Leaderboard`,`User`,`Score`) VALUES(" + (String)Leaderboard["ID"] + "," + this.UserID + "," + Score + ")");
}else{
// Existing entry found, update it if required
Hashtable CurrentEntry = EntryRes[0];
if(Score > int.Parse((String)CurrentEntry["Score"]))
this.main.Query("UPDATE `leaderboards_entries` SET `Score`=" + Score + " WHERE `ID`=" + (String)CurrentEntry["ID"]);
}
// Send back current location
int C = 0;
Hashtable[] Entries = this.main.Query("SELECT * FROM `leaderboards_entries` WHERE `Leaderboard`=" + (String)Leaderboard["ID"] + " ORDER BY `Score` DESC");
for(int i=0; i<Entries.Length; i++)
{
C++;
if(int.Parse((String)Entries[i]["User"]) == this.UserID)
{
this.Connection.Connection.Connection.Start_Send();
this.Connection.Connection.Connection.AddByte(42);
this.Connection.Connection.Connection.AddInt(C);
this.Connection.Connection.Connection.Finish_Send();
this.main.Log(this.Connection.IP + " (" + this.Username + ") submitted score " + Score + " for " + (String)Leaderboard["Name"] + ", making him #" + C);
break;
}
}
}
public void Packet_AvatarRequest(MrAG.Networking.Packet p){
string name = "";
try
{
name = p.ReadString();
}catch{
this.InvalidPacket();
return;
}
this.Connection.Connection.Connection.Start_Send();
this.Connection.Connection.Connection.AddByte(31);
this.Connection.Connection.Connection.AddString(name);
this.Connection.Connection.Connection.AddString(this.main.MD5((String)this.main.Query("SELECT * FROM `users` WHERE `Username`='" + this.main.Safe(name) + "' LIMIT 1")[0]["Email"]));
this.Connection.Connection.Connection.Finish_Send();
}
public void Packet_IngameChange(MrAG.Networking.Packet p){
bool playing;
short AppID;
try
{
playing = p.ReadBool();
AppID = p.ReadShort();
}catch{
this.InvalidPacket();
return;
}
this.main.Log("Player " + this.Username + " " + (playing ? "started" : "stopped") + " playing AppID " + AppID);
Hashtable[] gameRes = this.main.Query("SELECT * FROM `games` WHERE `ID`=" + AppID);
if(gameRes.Length == 0){
return;
}
Hashtable game = gameRes[0];
if (playing){
this.main.Query("UPDATE `users` SET `API_Playing`=" + AppID + " WHERE `ID`=" + this.UserID);
}else{
this.main.Query("UPDATE `users` SET `API_Playing`=0 WHERE `ID`=" + this.UserID);
}
Hashtable[] playingRes = this.main.Query("SELECT * FROM `playing` WHERE `User`=" + this.UserID + " AND `Game`=" + AppID);
if(playingRes.Length == 0)
{
this.main.Query("INSERT INTO `playing` (`User`,`Game`) VALUES(" + this.UserID + "," + AppID + ")");
}
foreach(User User in this.Friends)
{
User.Connection.Connection.Connection.Start_Send();
User.Connection.Connection.Connection.AddByte(8);
User.Connection.Connection.Connection.AddInt(this.UserID);
User.Connection.Connection.Connection.AddBool(playing);
if (playing){
User.Connection.Connection.Connection.AddShort(AppID);
}
User.Connection.Connection.Connection.Finish_Send();
}
this.Connection.Connection.Connection.Start_Send();
this.Connection.Connection.Connection.AddByte(14);
this.Connection.Connection.Connection.AddShort(AppID);
this.Connection.Connection.Connection.AddBool((String)game["Visible"] == "1" || (String)this.UserRow["Admin"] == "1");
this.Connection.Connection.Connection.Finish_Send();
}
public void Packet_ServerList(MrAG.Networking.Packet p)
{
string gameIdent = "";
try
{
gameIdent = p.ReadString();
}catch{
this.InvalidPacket();
return;
}
p.Start_Send();
p.AddByte(15);
int serverCount = 0;
foreach(ServerData server in this.main.Servers)
{
if(server.Game == gameIdent && server.lastUpdate > this.main.Epoch() - 30)
{
serverCount++;
}
}
p.AddInt(serverCount);
foreach(ServerData server in this.main.Servers)
{
if(server.Game == gameIdent && server.lastUpdate > this.main.Epoch() - 30)
{
p.AddString(server.IP);
p.AddInt(server.Port);
p.AddString(server.Name);
p.AddString(server.Meta);
p.AddInt(server.CurrentUsers);
p.AddInt(server.MaxUsers);
}
}
p.Finish_Send();
this.main.Log("Sent " + this.Username + " " + serverCount.ToString() + "/" + this.main.Servers.Count.ToString() + " servers for " + gameIdent + ".");
}
}
}

53
gServer/gServer.csproj Normal file
View File

@ -0,0 +1,53 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="3.5" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">x86</Platform>
<ProductVersion>9.0.21022</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{6F404B72-8B0D-4A82-BD61-5A5168EF8724}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>gServer</RootNamespace>
<AssemblyName>gServer</AssemblyName>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug</OutputPath>
<DefineConstants>DEBUG</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<PlatformTarget>x86</PlatformTarget>
<Externalconsole>true</Externalconsole>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
<DebugType>none</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Release</OutputPath>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<PlatformTarget>x86</PlatformTarget>
<Externalconsole>true</Externalconsole>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="MySql.Data, Version=1.0.10.1, Culture=neutral, PublicKeyToken=c5687fc88969c44d">
<SpecificVersion>False</SpecificVersion>
<HintPath>bin\Debug\MySql.Data.dll</HintPath>
</Reference>
<Reference Include="MrAG, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null">
<SpecificVersion>False</SpecificVersion>
<HintPath>bin\Debug\MrAG.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="Main.cs" />
<Compile Include="AssemblyInfo.cs" />
<Compile Include="User.cs" />
<Compile Include="ServerlistServer.cs" />
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
</Project>